2011-05-16 59 views
2

我有一個觀點,看起來像這樣:一組行的狀態合併成一個單一的彙總狀態

package_id package_line status_a  status_b 
1   1    NOT_STARTED  FAILED 
1   2    STARTED   STARTED 
1   3    FAILED   NOT_STARTED 
2   1    COMPLETE  STARTED 
2   2    COMPLETE  NOT_STARTED 

等,幾千行。 Status_a和status_b是單獨的不相關的狀態(實際上它們是在系統a和系統b上執行的包)。

我需要總結的的package_id,捲起到

package_id status_a status_b 
    1   FAILED FAILED 
    2   COMPLETE NOT_STARTED 

的規則組合包線

1. If any package line has failed, the package has failed. 
2. If all package lines are complete, the package is complete. 
3. If all package lines are NOT_STARTED, the package has not started. 
4. Otherwise, the package is started (i.e. a combination of started, not_started, and complete would summarize as STARTED). 

所以我想拿出一個查詢來創建此概要。我很想發佈代碼示例,但我真的很失落。據推測我想GROUP_BY package_id,但我可以使用什麼作爲一個聚合函數,使我可以應用列出的規則?

如果有幫助,我確實可以控制在包行級別報告狀態的方式,所以我可以報告數字狀態(儘管爲了理智,我喜歡讓它具有人類可讀性)。

回答

4

試試這個(同爲status_b):

SELECT package_id, 
     CASE WHEN FAILED_COUNT > 0 THEN 'FAILED' 
      WHEN COMPLETE_COUNT = ALL_COUNT THEN 'COMPLETE' 
      WHEN NOT_STARTED_COUNT = ALL_COUNT THEN 'NOT_STARTED' 
      ELSE 'STARTED' 
     END status_a 
FROM (   
SELECT package_id, 
    COUNT(status_a) ALL_COUNT, 
    SUM(CASE WHEN status_a = 'FAILED' THEN 1 ELSE 0 END) FAILED_COUNT, 
    SUM(CASE WHEN status_a = 'COMPLETE' THEN 1 ELSE 0 END) COMPLETE_COUNT, 
    SUM(CASE WHEN status_a = 'NOT_STARTED' THEN 1 ELSE 0 END) NOT_STARTED_COUNT, 
    SUM(CASE WHEN status_a = 'STARTED' THEN 1 ELSE 0 END) STARTED_COUNT 
FROM table 
GROUP BY package_id 
) 
+0

完美,謝謝!修復了一些錯位的逗號,以防其他人想要使用這一天。 – 2011-05-17 14:18:13

相關問題