2011-05-06 29 views
3

說我的表格只有2個字段:Idcolor根據同一表格的不同標準在相同字段中顯示的數量

id color 
---------- 
1 Green 
2 Red 
3 Yellow 

我希望計數顯示在一行而不是列中。

SELECT COUNT(color), color 
    FROM MYTABLE 
GROUP BY color 

這給了我:

count color 
-------------- 
10  Green 
20  Red 
15  Yellow 

我需要它顯示爲:

Green Red Yellow 
------------------- 
10  20 15 
+1

知道數據庫會有所幫助,但PIVOT標籤有信息如何做到這一點(以及覆蓋此問題的現有問題)。 – 2011-05-06 14:34:10

回答

1
select (select COUNT(color) from MyTable where color='Green') as 'Green', 
     (select COUNT(color) from MyTable where color='Red') as 'Red'. 
     (select COUNT(color) from MyTable where color='Yellow') as 'Yellow' 
1

另一種方式來做到這一點(在MySQL只)是:

SELECT SUM(color = 'Green') AS "Green" 
    , SUM(color = 'Red') AS "Red" 
    , SUM(color = 'Yellow') AS "Yellow" 
FROM MyTable ; 
3
SELECT 
    COUNT(CASE Color WHEN 'Green' THEN 1 END) AS Green, 
    COUNT(CASE Color WHEN 'Red' THEN 1 END) AS Red, 
    COUNT(CASE Color WHEN 'Yellow' THEN 1 END) AS Yellow 
FROM MYTABLE 

你不需要在這裏分組。基本上,每個COUNT通過所有行,但計數只有那些Color匹配某個值。

相關問題