2016-12-07 59 views
0

我的表是這樣的:選擇計數多列不同的列值

ID   Status 
----------- ----------------- 
a   3 
b   3 
c   1 
d   2 
e   1 

我如何可以查詢它使得對每種狀態的數在1列:

Status=1 Status=2 Status=3 
-------- -------- -------- 
2   1   2 

是它有必要Select從多個SelectCount在這裏? 注:狀態不是固定的,並且可以包含值除1,2和3

+0

是狀態列動態?這是否只包含1,2,3? –

+0

不,它不是修復 –

+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] 
3

嘗試此來實現,這是動態的

select 'Status = '+cast(Status as varchar(200)) Status,count(Status) Count from yourtable group by Status 
+1

Upvoted ...但改變結果格式..可能OP可以遵循這種格式,避免了硬編碼 –

+0

謝謝你的投票@prdp但將其轉換爲樞軸也會變得醜陋,所以我保持這種方式。 –