读书人

数据统计成效

发布时间: 2013-01-12 16:25:03 作者: rapoo

数据统计效果
表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


[解决办法]
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
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


哪里不一样了?
[解决办法]
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
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

读书人网 >SQL Server

热点推荐