读书人

这种统计如何写sql

发布时间: 2012-12-20 09:53:21 作者: rapoo

这种统计怎么写sql
数据表table1
部门 时间 级别 A类 B类
部门A .. 1 是
部门B .. 2 是
部门C .. 2 是
部门C .. 3 是

想统计各个部门 是A类和B类的数据次数
以上的数据 A类 部门A为0次 部门B为1次 部门C也为一次
B类 部门A为一次 部门B为0次 部门C为1次

[最优解释]
select 部门,A类=sum(case when A类='是' then 1 else 0 end),
B类=sum(case when B类='是' then 1 else 0 end)
from tb group by 部门
[其他解释]
我现在这么写 但是结果
A类 和B类 部门A 都为1次 部门B也都为1次 部门C都为2次了
sql语句:select 部门,COUNT(A类),COUNT(B类) from table1 group by 部门
[其他解释]

引用:
select 部门,A类=sum(case when A类='是' then 1 else 0 end),
B类=sum(case when B类='是' then 1 else 0 end)
from tb group by 部门

先谢谢了 效果出来了
还有个问题 要是想统计成这样 该怎么写呢??
所有部门 A部门 B部门 C部门 D部门
A类 2 0 1 1 0
B类 2 1 0 1 0
所有类 4 1 1 2 0
[其他解释]
引用:
引用:select 部门,A类=sum(case when A类='是' then 1 else 0 end),
B类=sum(case when B类='是' then 1 else 0 end)


from tb group by 部门
先谢谢了 效果出来了
还有个问题 要是想统计成这样 该怎么写呢??
……


说错了 这种效果现在不需要
1楼的结果统计出来了 那该怎么统计A类+B类的总和 ,部门+部门的总和呢?
select 部门,A类=sum(case when A类='是' then 1 else 0 end),
B类=sum(case when B类='是' then 1 else 0 end)
from tb group by 部门

读书人网 >SQL Server

热点推荐