我想获取出现在主组中的每个子组的计数。
给出以下内容:
| Clothing | Colour
-----------------------
| Shirt | black
| Shirt | black
| Shirt | black
| Shirt | yellow
| Shoes | yellow
| Shoes | yellow
| Shoes | black
我想要的输出是:
| A | B
---------------------------
| Shirt_Blacks | 3
| Shirt_Yellows | 1
| Shoes_Blacks | 1
| Shoes_Yellows | 2
编辑:输出格式2:
| Clothing | Black | Yellow
-----------------------------------
| Shirt | 3 | 1
| Shoes | 1 | 2
没有运气就尝试了以下内容:
SELECT COUNT(Colour)
FROM [randomtable]
Group By Clothing
答案 0 :(得分:1)
使用聚合:
SELECT CONCAT(Clothing, '_', Colour) A, COUNT(*) B
FROM mytable
GROUP BY Clothing, Colour
A | B :----------- | -: Shirt_black | 3 Shoes_black | 1 Shirt_yellow | 1 Shoes_yellow | 2
如果您希望透视结果集,则:
SELECT
Clothing,
SUM(CASE WHEN Colour = 'Black' THEN 1 ELSE 0 END) Black,
SUM(CASE WHEN Colour = 'Yellow THEN 1 ELSE 0 END) Yellow
FROM mytable
GROUP BY Clothing
答案 1 :(得分:1)
您可以按concat(衣服,“ _”,颜色)分组:
SELECT
concat(clothing, '_', colour) A,
COUNT(*) B
FROM [randomtable]
Group By concat(clothing, '_', colour)
答案 2 :(得分:0)
SELECT Clothing+'_'+Colour A, COUNT(*) B
FROM [randomtable]
GROUP BY Clothing+'_'+Colour
select * from [randomtable]
pivot
(count(colour) for colour in (black,yellow))AS piv