关于SQL函数count(*)的使用!

函数count能否实现一个表中两列数值的分别计数?
类似这个:
A B C D
a b 2 1
a b 2 1
a c 2 1
a b 1 2
a c 1 2
怎么用SQL统计出C列为2的数量和D列为2的数量
类似这样的结果
a b 2 1
a c 1 1
A,B列为a,b的情况下 C列为2的数量是2个,D列为2的数量是1个.
下边那行结果同理!A,B列为a,c的情况下C列为2的数量为1,D列为2的数量为1.

第1个回答  推荐于2016-09-05
select sum(case when(C=2) then 1 else 0 end) count_C,sum(case when(D=2) then 1 else 0 end) count_D from 表 where A='a' and B='c'

这样得到的count_C和count_D就是统计出来的C和D列的值。追问

这样取值取得只是当A列为a,B列为c时候的值吧?

追答

如果你想把所有结果都列出来那就加个group by吧

select A,B, sum(case when(C=2) then 1 else 0 end) count_C,sum(case when(D=2) then 1 else 0 end) count_D from 表 group by A,B

本回答被提问者采纳
第2个回答  2012-12-22
是这样吗:
select sum(case when a=b then 1 else 0 end) 相同数
from table追问

不是这样的...

追答

select a,b,sum(case when c=2 then 1 else 0 end),
sum(case when d=2 then 1 else 0 end)
from table
group a,b

相似回答