函数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.
这样取值取得只是当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
不是这样的...
追答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