2017-03-21 116 views
1

我有一個關於查詢數據的問題。當我想從以下數據mysql根據值顯示列

id item color 
1 card red 
2 card red 
3 card blue 
4 card blue 
5 light red 
6 light blue 
7 light yellow 
8 cup red 
9 cup red 
10 cup blue 

獲得熱銷項目的特定顏色(紅色和藍色),其計爲這種格式

item red blue 
card 2 2 
light 1 1 
cup  2 0 

我從這個開始。

select item ,color, count(*) from shops where color in ('red','blue') group by item , color 

但是當我試圖將「紅色」,「藍色」分隔成2列時。我不知道該怎麼做。如果有人能爲此問題提供一些關鍵字或方向,我將不勝感激。

回答

3

您可以使用此:

SELECT item, 
    SUM(CASE WHEN color = 'red' THEN 1 ELSE 0 END) AS red, 
    SUM(CASE WHEN color = 'blue' THEN 1 ELSE 0 END) AS blue 
FROM table_name 
GROUP BY item; 
0

嘗試用兩項罪名,用的情況下,在其內部:

select item, 
     count(case when color = 'red' then item end) as red, 
     count(case when color = 'blue' then item end) as blue 
from shops 
group by item 
+1

也許總和(情況下,當色= '紅',那麼1點否則爲0結束)作爲紅色 –

+0

計數項目的顏色是否爲紅色,否則爲空?空值將計爲0 –