2013-09-25 123 views
1

我正在尋找基於3種不同條件(DB2數據庫)的項目計數。我需要統計所有項目< = .10,> = .5和> = 1.00(percentage_used),但只能按dim_building_id和building_name進行分組。當然,這個查詢將不會運行,因爲它需要percentage_used被添加到組中。如何處理percentage_used這3個條件?Count,Having和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, 


       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

我會做這樣的事情:

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 
+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, 
+0

這兩個答案的工作。先與誰回答。謝謝。 – Tone

+0

其實,你選了最後一個,但很樂意幫忙。 –