我有一个这样的数据库:
id | name | type | approval
1 | a | red | 0
2 | b | blue | null
3 | c | grey | 1
4 | d | red | null
5 | e | blue | 1
6 | f | grey | 1
然后,我想要一个输出来计算每个批准值(null:pending,0:denied,1:approved),如下所示:
type | pending | denied | approved
red | 1 | 1 | 0
blue | 1 | 0 | 1
grey | 0 | 0 | 2
我不是sql的专家,我可以使用sql生成这样的输出吗?如果有,请告诉我。如果需要一些编程语言,请告诉我。感谢。
答案 0 :(得分:1)
试试这个:
select type,
sum(if(approval is null, 1, 0)) as pending,
sum(if(approval=0, 1, 0)) as denied,
sum(if(approval=1, 1, 0)) as approval
from test
group by type
在小提琴上看到它:http://sqlfiddle.com/#!2/a9348e/4
如果你想要确切的订单?添加order by if( type='red', 1 ,if(type='blue',2,3) )