Count,Having和Case声明

时间:2013-09-25 16:49:18

标签: sql group-by db2 case having

我希望根据3种不同的条件(DB2数据库)生成一系列项目。我需要计算所有项目< = .10,> = .5和> = 1.00(percentage_used),但只能按dim_building_id和building_name进行分组。当然,此查询不会运行,因为它需要将percentage_used添加到组中。如何使用percentage_used处理这3个条件?

SELECT
SUM(CAST(FTS.GROUP_A AS BIGINT)) AS GROUP_A,
        SUM(CAST(FTS.GROUP_B AS BIGINT)) AS GROUP_B,
        SUM(CAST(FTS.GROUP_C AS BIGINT)) AS GROUP_C,


                CASE WHEN FAT.PERCENTAGE_USED <= '0.10'
                THEN COUNT(*)
                END AS PROJECTS_L10,
                CASE WHEN FAT.PERCENTAGE_USED >= '0.50' 
                THEN COUNT(*)
                END AS PROJECTS_G50,
                CASE WHEN FAT.PERCENTAGE_USED >= '1.00' 
                THEN COUNT(*)
                END AS PROJECTS_G100,
        DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE)  AS DAYS_LEFT,
        (DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE))/7 AS WEEKS_LEFT, 
        DAYS(DATE('2013-12-31')) - DAYS(CURRENT DATE) AS DAYS_LEFT_YEAR      

FROM FACT_TABLE AS FAT
INNER JOIN GROUPS AS FTS ON FAT.DIM_PROJECT_ID = FTS.DIM_PROJECT_ID
GROUP BY FAT.DIM_BUILDING_ID, FAT.BUILDING_NAME;

2 个答案:

答案 0 :(得分:2)

不是将聚合作为THEN,而是将CASE语句包装在聚合中:

SELECT
SUM(CAST(FTS.GROUP_A AS BIGINT)) AS GROUP_A,
        SUM(CAST(FTS.GROUP_B AS BIGINT)) AS GROUP_B,
        SUM(CAST(FTS.GROUP_C AS BIGINT)) AS GROUP_C,  
        SUM(CASE WHEN FAT.PERCENTAGE_USED <= '0.10' THEN 1 ELSE 0 END) AS PROJECTS_L10,
        SUM(CASE WHEN FAT.PERCENTAGE_USED >= '0.50' THEN 1 ELSE 0 END) AS PROJECTS_G50,
        SUM(CASE WHEN FAT.PERCENTAGE_USED >= '1.00' THEN 1 ELSE 0 END) AS PROJECTS_G100,
        DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE)  AS DAYS_LEFT,
        (DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE))/7 AS WEEKS_LEFT, 
        DAYS(DATE('2013-12-31')) - DAYS(CURRENT DATE) AS DAYS_LEFT_YEAR      

FROM FACT_TABLE AS FAT
INNER JOIN GROUPS AS FTS ON FAT.DIM_PROJECT_ID = FTS.DIM_PROJECT_ID
GROUP BY FAT.DIM_BUILDING_ID, FAT.BUILDING_NAME;

不需要ELSE 0,但有些人喜欢在查询中看到它。

或者这也应该有效:

COUNT(CASE WHEN FAT.PERCENTAGE_USED >= '0.50' THEN 1 END) AS PROJECTS_G50,

答案 1 :(得分:2)

我会做这样的事情:

select bn.building_name ,
       t.*
from ( select fat.building_id ,
              sum( case when fat.percentage_used <= 0.10                                then 1 else 0 end ) as group_a ,
              sum( case when fat.percentage_used >  0.10 and fat.percentage_used < 0.50 then 1 else 0 end ) as group_b ,
              sum( case when fat.percentage_used >= 0.50 and fat.percentage_used < 1.00 then 1 else 0 end ) as group_c ,
              sum( case when fat.percentage_used >= 1.00                                then 1 else 0 end ) as group_d ,
              sum( case when fat.percentage_used is null                                then 1 else 0 end ) as group_e
       from fact_table fat
       join groups     fts on tfs.dim_project_id = fat.dim_project_id
       group by fat.building_id
     ) t
join fact_table bn on bn.building_id = t.building_id