SQL显示行中数据的总和

时间:2013-07-14 08:48:46

标签: sql sql-server

我有一张这样的表

No.
--
b
r
g
g
r
b
r
g

我想要结果集如下

Type of color | Ocurrence
Blue              2
green             3
red               3
TOTAL             8

请帮忙

2 个答案:

答案 0 :(得分:4)

听起来像CASEGROUP 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;

An SQLfiddle to test with

要得到一个总数,一个(不一定是最简单的)方式就是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;

Another SQLfiddle

答案 1 :(得分:2)

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