有一句SQL语句关于时间段统计求和的问题,不知怎么写?感觉很难!谢谢!

87607047 2006-09-22 10:41:13

有一个每天的数据的表as_d9902,
日期 客户帐号 金额
mdic acno acbl

关系表
as_relation
客户帐号 起始日期 截止日期 员工号
acno stdt eddt empl_id

员工部门表 as_emplstay
员工号 起始日期 截止日期 部门
empl_id stdt eddt dept_id

意思是说:客户与员工关联是有时间段的,员工与部门也是有时间段的

现在是当时的实际的情况,求出部门的该时间段的金额的汇总数和当前日期的总数

我写了这么一句,不知对不对:

select dept_id,sum(acbl) sumacbl,sum(case where a.mdic='20060921' then a.acbl else 0) acbl from as_d9902 a, as_relation b ,as_emplstay c where

a.mdic>='20060131' and a.mdic<='20060921' and a.acno=b.acno and b.empl_id=c.empl_id

and a.mdic>=b.stdt and a.mdic<=b.eddt and a.mdic>=c.stdt and a.mdic<=c.eddt group by dept_id

不知这样写对不对?特请教!

谢谢!



...全文
391 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengda1i 2006-09-23
  • 打赏
  • 举报
回复
速度吗

加索引

as_d9902(mdic,acno)
as_relation(stdt,eddt,acno,empl_id)
as_emplstay(stdt,eddt,empl_id,dept_id)

lxzm1001 2006-09-23
  • 打赏
  • 举报
回复
应该不会慢很多吧!
87607047 2006-09-23
  • 打赏
  • 举报
回复
有没有办法让速度快一点?
我现在把这个去掉,速度还是很慢
select dept_id,sum(acbl*b.[percent]) sumacbl,sum(case when a.mdic='20060921' then a.acbl*b.[percent] else 0 end) acbl
from as_d9902 a
join as_relation b on a.acno=b.acno
join as_emplstay c on b.empl_id=c.empl_id
where a.mdic>='20060131' and a.mdic<='20060921'
--and a.mdic>=b.stdt and a.mdic<=b.eddt and a.mdic>=c.stdt and a.mdic<=c.eddt
group by dept_id

还有不知为什么?
select * from as_d9902 where mdic='20060921' 这样速度会很快
但 select * from as_d9902 where mdic>='20060921' and mdic<='20060922' 这样速度会很慢
谢谢!
xiaoku 2006-09-23
  • 打赏
  • 举报
回复
a.mdic>=b.stdt and a.mdic<=b.eddt and a.mdic>=c.stdt and a.mdic<=c.eddt

这个条件是比较慢的...
xiaoku 2006-09-23
  • 打赏
  • 举报
回复
这么查询是没什么问题吧,不过略显凌乱!

select dept_id,sum(acbl*b.[percent]) sumacbl,sum(case where a.mdic='20060921' then a.acbl*b.[percent]) else 0) acbl
from as_d9902 a,
join as_relation b on a.acno=b.acno
join as_emplstay c on b.empl_id=c.empl_id
where a.mdic>='20060131' and a.mdic<='20060921'
and a.mdic>=b.stdt and a.mdic<=b.eddt and a.mdic>=c.stdt and a.mdic<=c.eddt
group by dept_id
87607047 2006-09-22
  • 打赏
  • 举报
回复
应当是这样的,因为当天的一个客户可能属于一个或多个人的,但有一个比例关系(总和只能等于1),而且在一段时间内,一个人只能属于一个部门,不会在同一时间段属于两个部门的,

数据的表as_d9902
日期 客户帐号 金额 比例
mdic acno acbl percent


select dept_id,sum(acbl*b.[percent]) sumacbl,sum(case where a.mdic='20060921' then a.acbl*b.[percent]) else 0) acbl from as_d9902 a, as_relation b ,as_emplstay c where

a.mdic>='20060131' and a.mdic<='20060921' and a.acno=b.acno and b.empl_id=c.empl_id

and a.mdic>=b.stdt and a.mdic<=b.eddt and a.mdic>=c.stdt and a.mdic<=c.eddt group by dept_id


pengda1i 2006-09-22
  • 打赏
  • 举报
回复
如果你保证每个
mdic acno 组合都能在关系表找到一条记录
而且,每个
mdic empl_id组合都能在员工部门表 找到一条记录

你的语句就是对的

这里 找到一条记录 指的是有且只有一条

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧