我正在使用 db2 数据库(不确定版本)。我的脚本可以正常工作,但我没有产生我期望的结果。我需要根据我的案例陈述中的条件将我的总计分为 3 组,但是对于相同 project_name/id 和 building_name/id 下的每个项目,我需要每个存储桶下的总和,每个 project_name/id 只有一行,并且building_name/id。我假设某种类型的分组或递归函数将是解决方案,但我不太确定。将不胜感激推动正确的方向。这是我的脚本。
SELECT
DP.DIM_PROJECT_ID,
DP.PROJECT_NAME,
DM.DIM_BUILDING_ID,
DM.BUILDING_NAME,
CASE WHEN ( DJ.GROUPS3 IN ('33.3% <= x <= 100%', '16.7% <= x < 33.3%') AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
WHEN (DJ.GROUPS3 IN ('60% <= x <= 100%', '20% <= x < 60%') AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
ELSE '0'
END as CAPABILITY,
CASE WHEN (DJ.GROUPS3 = '0% <= x < 16.7%' AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
WHEN (DJ.GROUPS3 = '0% <= x < 20%' AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
ELSE '0'
END as GROUP_1,
CASE WHEN (DJ.GROUPS3 = '16.7% <= x < 33.3%' AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
WHEN (DJ.GROUPS3 = '20% <= x < 60%' AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
ELSE '0'
END as GROUP_2,
CASE WHEN (DJ.GROUPS3 = '33.3% <= x <= 100%' AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
WHEN (DJ.GROUPS3 = '60% <= x <= 100%' AND DA.TYPE_NAME = 'SALES')
THEN cast(sum(cast(FAT.TRANSACTION_AMOUNT as real)) as integer)
ELSE '0'
END as GROUP_3
FROM FACT_TABLE as FAT
RIGHT JOIN DIM_ALLOCATION DA ON FAT.DIM_ALLOCATION_ID = DA.DIM_ALLOCATION_ID
INNER JOIN DIM_PROJECT DP ON FAT.DIM_PROJECT_ID = DP.DIM_PROJECT_ID
INNER JOIN DIM_DATE DD ON FAT.ALLOCATION_START_DATE_DIM_ID = DD.DATE_KEY
INNER JOIN DIM_JOB DJ ON FAT.DIM_JOB_ID = DJ.DIM_JOB_ID
INNER JOIN DIM_BUILDING DM ON FAT.DIM_BUILDING_ID = DM.DIM_BUILDING_ID
WHERE
DD.DATE_VALUE = '2013'
AND DA.BUILDING_NAME IN ('ADMIN', 'INVISION')
GROUP BY DM.DIM_BUILDING_ID,
DP.DIM_PROJECT_ID,
DP.PROJECT_NAME,
CAPABILITY,
DM.BUILDING_NAME,
DJ.GROUPS3,
DA.TYPE_NAME
ORDER BY DP.PROJECT_NAME
结果:
期望的结果: