如何按

时间:2016-03-04 01:15:46

标签: sql oracle

我有下表:

Table

我希望得到三组年龄的sum A B | C D | E F

我该怎么做?

2 个答案:

答案 0 :(得分:1)

WITH sample_data AS
  (SELECT 1 AS id, 10 AS age, 11 AS name, 'A' AS type FROM dual
  UNION ALL
  SELECT 2, 0, 1, 'B' FROM dual
  UNION ALL
  SELECT 3, 9, 11, 'C' FROM dual
  UNION ALL
  SELECT 4, 10, 11, 'D' FROM dual
  UNION ALL
  SELECT 5, 10, 11, 'E' FROM dual
  UNION ALL
  SELECT 6, 10, 11, 'F' FROM dual
  )
SELECT listagg(type,',') within GROUP (
ORDER BY type) types,
  SUM(age)
FROM sample_data
GROUP BY DECODE(type,'A',1,'B',1,'C',2,'D',2,3)

结果

types    sum(age)
A,B        10
C,D        19
E,F        20

答案 1 :(得分:0)

以下内容应该为您提供所需内容:

SELECT CASE
         WHEN TYPE IN ('A', 'B') THEN 'AB'
         WHEN TYPE IN ('C', 'D') THEN 'CD'
         WHEN TYPE IN ('E', 'f') THEN 'Ef'
       END AS KIND,
       SUM(AGE) AS TOTAL_AGES
  FROM WHATEVER_TABLE
  GROUP BY CASE
             WHEN TYPE IN ('A', 'B') THEN 'AB'
             WHEN TYPE IN ('C', 'D') THEN 'CD'
             WHEN TYPE IN ('E', 'f') THEN 'Ef'
           END;