我有一张这样的桌子
No.
--
b
r
g
g
r
b
r
g
我想要如下结果集
Type of color | Ocurrence
Blue 2
green 3
red 3
TOTAL 8
请帮忙
我有一张这样的桌子
No.
--
b
r
g
g
r
b
r
g
我想要如下结果集
Type of color | Ocurrence
Blue 2
green 3
red 3
TOTAL 8
请帮忙
听起来像CASE
并且GROUP BY
将是您所需要的;
SELECT
CASE WHEN color = 'r' THEN 'red'
WHEN color = 'g' THEN 'green'
WHEN color = 'b' THEN 'blue'
END "Type of color", COUNT(color) "Occurrence"
FROM Table1
GROUP BY color
ORDER BY color;
要获得总数,一种(不一定是最简单的)方法是将 UNION 与总数合并;
WITH cte AS (
SELECT
CASE WHEN color = 'r' THEN 'red'
WHEN color = 'g' THEN 'green'
WHEN color = 'b' THEN 'blue'
END "Type of color", COUNT(color) "Occurrence"
FROM Table1
GROUP BY color
UNION
SELECT 'TOTAL',COUNT(*)
FROM Table1
)
SELECT * FROM cte
ORDER BY CASE WHEN "Type of color" = 'TOTAL' THEN 1 END;
Joachim 的回答很好,除了有一种更简单的方法可以使用以下方法获得总数rollup
:
SELECT
CASE WHEN color = 'r' THEN 'red'
WHEN color = 'g' THEN 'green'
WHEN color = 'b' THEN 'blue'
when color is NULL then 'Total'
END "Type of color", COUNT(*) "Occurrence"
FROM Table1
GROUP BY color with rollup
ORDER BY (case when color is null then 1 else 0 end), color