2017-03-21 129 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 –