根据条件求和

时间:2013-09-24 15:04:45

标签: function db2 aggregate-functions recursive-query

我正在使用db2数据库(不确定版本)。我的脚本功能正常,但我没有产生我期望的结果。我需要根据我的case语句中的条件将我的总计总数分成3组,但对于同一project_name / id和building_name / id下的每个项目,我需要每个bucket下的总和,每个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

结果: enter image description here

期望的结果: enter image description here

1 个答案:

答案 0 :(得分:0)

我找到了答案并将其发布在下面。

cast(SUM(CASE WHEN DJ.GROUPS3 IN ('33.3% <= x <= 100%', '16.7% <= x < 33.3%')
    THEN cast(FAT.TRANSACTION_AMOUNT as real)
    WHEN DJ.GROUPS3 IN ('60% <= x <= 100%', '20% <= x < 60%')
    THEN cast(FAT.TRANSACTION_AMOUNT as real)
    ELSE NULL
    END)) as integer)  as CAPABILITY,

你拿出总和并在案例陈述之外抛弃。