我选择了......
SELECT colors,
COUNT (Num1) AS number1,
COUNT (Num2) AS number2,
COUNT (Num3) AS number3,
COUNT (Num4) AS number4
From table
Group By colors
结果将是:
我的问题是: 如果没有显示某些颜色,如何在包含该计数(0 0 0 0)的颜色的结果末尾添加一行? 注意:所有颜色必须显示在结果中,但不是所有颜色都必须写在表
中答案 0 :(得分:1)
您可以将LEFT JOIN
用于返回所有可能颜色的子查询:
SELECT s.color,
COUNT (t.Num1) AS number1,
COUNT (t.Num2) AS number2,
COUNT (t.Num3) AS number3,
COUNT (t.Num4) AS number4
FROM (-- subquery or table of all possible colors
) s
LEFT JOIN table t
ON s.color = t.color
GROUP BY s.color;
<强> Rextester Demo 强>
修改强>
或使用UNION ALL:
WITH cte AS (
SELECT t.color,
COUNT (t.Num1) AS number1,
COUNT (t.Num2) AS number2,
COUNT (t.Num3) AS number3,
COUNT (t.Num4) AS number4
FROM table t
GROUP BY t.color
)
SELECT *
FROM cte
UNION ALL
SELECT color, 0, 0, 0, 0
FROM (--table or subquery) s
WHERE NOT EXISTS (SELECT *
FROM cte c
WHERE c.color = s.color);
<强> Rextester Demo 2 强>