将多个 SUM(CASE) 添加到同一列

Adding Multiple SUM(CASE)s to Same Column

我在 DB2 中有以下 table:

COLUMN_NAME DATA_TYPE TYPE_NAME COLUMN_SIZE COLUMN_TEXT
DMYEAR 3 DECIMAL 4 Fiscal Year
DMYTYP -2 CHAR () FOR BIT DATA 1 Year Type
DMPTYP -2 CHAR () FOR BIT DATA 1 Period Type
DMTYPE -2 CHAR () FOR BIT DATA 6 Type of Data
DMPROD -2 CHAR () FOR BIT DATA 35 Product Code
DMVL01 3 DECIMAL 17 Value Period 1
DMVL02 3 DECIMAL 17 Value Period 2
DMVL03 3 DECIMAL 17 Value Period 3
DMVL04 3 DECIMAL 17 Value Period 4
DMVL05 3 DECIMAL 17 Value Period 5
DMVL06 3 DECIMAL 17 Value Period 6
DMVL07 3 DECIMAL 17 Value Period 7
DMVL08 3 DECIMAL 17 Value Period 8
DMVL09 3 DECIMAL 17 Value Period 9
DMVL10 3 DECIMAL 17 Value Period 10
DMVL11 3 DECIMAL 17 Value Period 11
DMVL12 3 DECIMAL 17 Value Period 12

取值周期为一月到二月,可以汇总每个月的各种数据类型,如下所示:

SELECT 
DMYEAR,
DMPTYP,
DMPROD,
Sum(CASE WHEN DMTYPE = 'COST' THEN DMVL01 ELSE 0 END) AS COST,
Sum(CASE WHEN DMTYPE = 'COST' THEN DMVL02 ELSE 0 END) AS COST,
Sum(CASE WHEN DMTYPE = 'COST' THEN DMVL03 ELSE 0 END) AS COST,
Sum(CASE WHEN DMTYPE = 'RTNCST' THEN DMVL01 ELSE 0 END) AS RTNCST,
Sum(CASE WHEN DMTYPE = 'RTNCST' THEN DMVL02 ELSE 0 END) AS RTNCST,
Sum(CASE WHEN DMTYPE = 'RTNCST' THEN DMVL03 ELSE 0 END) AS RTNCST
FROM DWM
WHERE DMPTYP = 'M' 
GROUP BY DMYEAR, DMPTYP, DMPROD
ORDER BY 1, 3

产生这样的输出:

DMYEAR DMPTYP DMPROD COST COST COST RTNCST RTNCST RTNCST
2010 M 11105 435798.00000 441252.00000 479774.00000 -2921.00000 0.00000 0.00000
2010 M 11350 538938.00000 593764.00000 511088.00000 -4074.00000 -2503.00000 0.00000
2010 M 11364 2905557.00000 3167448.00000 3534924.00000 -5691.00000 0.00000 0.00000
2010 M 11374 854274.00000 829392.00000

但我想为表示 1-12 的月份创建一个新列并调整总和以生成相应的值,因此它看起来像这样:

DMYEAR DMMONTH DMPTYP DMPROD COST RTNCST
2011 1 M 11105 278021.00000 -7522.00000
2011 2 M 11105 615232.00000 -938.00000
2011 3 M 11105 2153272.00000 -2805.00000

我认为子查询是可行的,但请记住我有 8-9 个不同的 DMTYPE,所以我希望有一个比为每个 DMTYPE 制作 9 个 case 语句更优雅的解决方案。

尝试将相应的表达式添加到内部 CASE 以获得所有 12 个 (x, DMVLx) 对:

WITH 
  T (DMMONTH) AS (VALUES 1 UNION ALL SELECT DMMONTH + 1 FROM T WHERE DMMONTH < 12)
SELECT 
  DMYEAR, DMMONTH, DMPTYP, DMPROD
, Sum (CASE WHEN DMTYPE = 'COST'   THEN CASE DMMONTH WHEN 1 THEN DMVL01 WHEN 2 THEN DMVL02 ... WHEN 12 THEN DMVL12 END ELSE 0 END) AS COST
, Sum (CASE WHEN DMTYPE = 'RTNCST' THEN CASE DMMONTH WHEN 1 THEN DMVL01 WHEN 2 THEN DMVL02 ... WHEN 12 THEN DMVL12 END ELSE 0 END) AS RTNCST
FROM DWM, T
WHERE DMPTYP = 'M' 
GROUP BY DMYEAR, DMMONTH, DMPTYP, DMPROD
ORDER BY 1, 3