我有一个关于查询数据的问题。当我想从以下数据中获取销售商品的特定颜色(红色和蓝色)及其计数时
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
但是当我试图分开" red"," blue"分为2列。我不知道该怎么做。如果有人可以为这个问题提供一些关键词或方向,我将不胜感激。
答案 0 :(得分: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;
答案 1 :(得分: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