我有这样的表:
ID Status
----------- -----------------
a 3
b 3
c 1
d 2
e 1
我如何查询它,使每个状态的计数在1列中:
Status=1 Status=2 Status=3
-------- -------- --------
2 1 2
是否有必要Select
来自Select
Count
多个GetDeviceInfo
?
注意:状态不是固定的,可能包含除1,2和3之外的值
答案 0 :(得分:4)
使用条件聚合
select count(case when Status = 1 then 1 end) as [Status=1],
count(case when Status = 2 then 1 end) as [Status=2],
count(case when Status = 3 then 1 end) as [Status=3]
From yourtable
可以通过SUM
汇总
Sum(case when Status = 1 then 1 else 0 end) as [Status=1]
答案 1 :(得分:3)
试试这个,这是动态的
select 'Status = '+cast(Status as varchar(200)) Status,count(Status) Count from yourtable group by Status