2013-04-29 98 views
3
SELECT COUNT(Type) from House where Type = 1 
SELECT COUNT(Type) from House where Type = 2 
SELECT COUNT(Type) from House where Type = 3 

我的問題是:我想參加以上3條語句獲得:3列,即如: ColumnType1: '50',ColumnType2: '60',columnType3:「 45'加入select語句得到的SQL列

感謝

回答

3

您可以使用一個聚合F中的列結了CASE表達:

SELECT 
    count(case when Type = 1 then Type end) as type_1, 
    count(case when Type = 2 then Type end) as type_2, 
    count(case when Type = 3 then Type end) as type_3 
from House 
+0

嗨,我需要你的幫助。我創建了一個[動態查詢](http://www.sqlfiddle.com/#!2/10bc2/17),它工作正常。但是當動態值有一個*空格*時(例如* channel *'unknown 01'在這個例子中,它[不起作用](http://www.sqlfiddle.com/#!2/6ff09/1) )。任何解決方案 – hims056 2013-04-29 13:29:55

+1

@ hims056你最好用反引號包裝列名 - http://www.sqlfiddle.com/#!2/6ff09/2 – Taryn 2013-04-29 14:16:53

1

您可以使用case加起來如果Type比賽

SELECT sum(case when Type = 1 then 1 else 0 end) as type_1, 
     sum(case when Type = 2 then 1 else 0 end) as type_2, 
     sum(case when Type = 3 then 1 else 0 end) as type_3 
from House 
0
SELECT 
    COUNT(Type) as val1, 
    (SELECT COUNT(Type) from House where Type = 2) as val2, 
    (SELECT COUNT(Type) from House where Type = 3) as val3 
from House where Type = 1 
1

有一種清潔型SQL的,可以給你這個答案,但你必須在不同的行中的每個類型:

SELECT Type, COUNT(Type) FROM House GROUP BY Type 

它按照您的要求不給您列的缺點;但優點是它適用於任何數量的不同類型,而無需更改查詢。