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

数据统计效果
表table1
 ljbz    bzName
 101      A级
 102      B级
 103      C级
 104      D级
 表table2
 id      Dname         bzName      WT
 1        部门A           D级        是
 2        部门B           C级        是
 3        部门C           A级        否
 需要统计  部门完成的级别次数(table2表中有几个部门就统计几个部门)    条件WT=是算1次  
 统计成
               A级       B级      C级      D级
部门A        0         0         0           1
部门B        0         0         1           0
部门C        0         0         0           0

求解..

------解决方案--------------------

select Dname,count(case when bzName='A级' and WT='是' then 1 else null end) as A级,
             count(case when bzName='B级' and WT='是' then 1 else null end) as B级,
             count(case when bzName='C级' and WT='是' then 1 else null end) as C级,
             count(case when bzName='D级' and WT='是' then 1 else null end) as D级
             from table2
group by Dname

------解决方案--------------------
(table2表中有几个部门就统计几个部门) 用动态语句吧。
------解决方案--------------------
union all
select '所有部门 ',sum(case when bzName='A级' and WT='是' then 1 else 0 end),sum(case when bzName='B级' and WT='是' then 1 else 0 end) as B级,
             sum(case when bzName='C级' and WT='是' then 1 else 0 end) as C级,
             sum(case when bzName='D级' and WT='是' then 1 else 0 end) as D级   from table2