日期:2014-05-17  浏览次数:20507 次

急!帮忙看一个sql统计查询语句
select t1.*
,sum(case when t1.userid=t2.ckuser and t2.ckdate>='2012-11-01' and t2.ckdate<'2012-11-18' 
then t2.ckcount else 0 end) 
 as ckcount
,isnull((t1.salary/ckcount),0) as getpj from(select tb1.userid,tb1.username,
sum(case when tb1.userid=tb2.procpuser and tb2.procpdate>='2012-11-01' and tb2.procpdate<'2012-11-18'
 then tb2.procpcount else 0 end) as processcount,sum(case when tb1.userid=tb2.procpuser 
and tb2.procpdate>='2012-11-01' and tb2.procpdate<'2012-11-18' then tb2.procpcount*tb4.fpsalary else 0 end)
 as salary From ((userinfo tb1 left join pro_complete tb2 on tb1.userid=tb2.procpuser) 
left join process tb3 on tb2.procpprocess=tb3.proid) left join flow_pro tb4 on tb2.procpflow=tb4.fpflow 
and tb2.procpprocess=tb4.fpprocess where 1=1 group by userid,username) t1 
left join user_checkin t2 on t1.userid=t2.ckuser 
group by userid,username,processcount,salary
,ckcount

上面有一个字段ckcount字段,统计的时候 要进行合计每个userid的ckcount总和,但是 按照我上面的方法写的话查询结果当同一个userid出现不同的ckcount记录时就会出现多条userid记录显示不同ckcount的合计,如果修改才能避免出现这种状况准确的查询每个员工的ckcount合计?
------解决方案--------------------
select t1.*
 ,sum(case when t1.userid=t2.ckuser and t2.ckdate>='2012-11-01' and t2.ckdate<'2012-11-18' 
 then t2.ckcount else 0 end) 
  as ckcount
 ,isnull((t1.salary/ckcount),0) as getpj from(select tb1.userid,tb1.username,
 sum(case when tb1.userid=tb2.procpuser and tb2.procpdate>='2012-11-01' and tb2.procpdate<'2012-11-18'
  then tb2.procpcount else 0 end) as processcount,sum(case when tb1.userid=tb2.procpuser 
 and tb2.procpdate>='2012-11-01' and tb2.procpdate<'2012-11-18' then tb2.procpcount*tb4.fpsalary else 0 end)
  as salary From ((userinfo tb1 left join pro_complete tb2 on tb1.userid=tb2.procpuser) 
 left join process tb3 on tb2.procpprocess=tb3.proid) left join flow_pro tb4 on tb2.procpflow=tb4.fpflow 
 and tb2.procpprocess=tb4.fpprocess where 1=1 group by userid,username) t1 
 left join user_checkin t2 on t1.userid=t2.ckuser 
 group by userid,username,processcount,salary
 ,ckcount
把分组里的ckcount 去掉就好了