2014-04-25 59 views
0

我有一個統計值的特定類型的數據的查詢:請在SQL查詢的條目

SELECT 

B.BG_USER_05 as Functionality, 
count(case when bg_status= 'New' then 1 end) as 'New', 
count(case when bg_status= 'Open' then 1 end) as 'Open', 
count(case when bg_status= 'Assigned' then 1 end) as 'Assigned', 
count(case when bg_status= 'Fixed' then 1 end) as 'Fixed', 
count(case when bg_status= 'Ready to Test' then 1 end) as 'Ready_to_Test', 
count(case when bg_status= 'Reopen' then 1 end) as 'Reopen', 
count(case when bg_status= 'Closed' then 1 end) as 'Closed', 
count(case when bg_status= 'Rejected' then 1 end) as 'Rejected' 

FROM 
    BUG B, 
    RELEASES R 

WHERE 
    B.BG_DETECTED_IN_REL = R.REL_ID 

GROUP BY 
    B.BG_USER_05 

查詢工作正常,返回是這樣的:

UAT 5 13 2 3 0 
SIT 14 82 59 18 8 

問題是,有時,表中沒有UAT元素(這是完全正常的),這會使結果如下所示:

SIT 14 82 59 18 8 

的問題是,我需要的拳頭行是UAT信息,我需要的結果是事端這樣的:

UAT 0 0 0 0 0 
SIT 14 82 59 18 8 

我不知道如何處理這個。 有什麼想法?

回答

1

可以使用left outer join解決這個問題:

SELECT u.Functionality, 
     count(case when bg_status= 'New' then 1 end) as "New", 
     count(case when bg_status= 'Open' then 1 end) as "Open", 
     count(case when bg_status= 'Assigned' then 1 end) as "Assigned", 
     count(case when bg_status= 'Fixed' then 1 end) as "Fixed", 
     count(case when bg_status= 'Ready to Test' then 1 end) as "Ready_to_Test", 
     count(case when bg_status= 'Reopen' then 1 end) as "Reopen", 
     count(case when bg_status= 'Closed' then 1 end) as "Closed", 
     count(case when bg_status= 'Rejected' then 1 end) as "Rejected" 
FROM (SELECT 'UAT' as functionality UNION ALL SELECT 'SIT') as u LEFT OUTER JOIN 
    BUG B 
    ON u.functionality = B.BG_USER_05 LEFT OUTER JOIN 
    RELEASES R 
    ON B.BG_DETECTED_IN_REL = R.REL_ID 
GROUP BY u.functionality; 

我也改爲使用顯式連接語法(其中條件是on子句中的查詢)。而且,列別名使用雙引號而不是單引號。單引號只能用於字符串和日期常量;他們對標識符的使用常常導致混淆。

+0

不得不從查詢中刪除雙引號(因爲查詢是在Excel單元格內編寫的,並且在雙引號內部......可怕的東西,我知道),所以它像一個魅力一樣工作。謝謝! – Leo

0

也許,這樣的事情:

SELECT Functionality, sum('New'), sum('Open'),sum('Assigned'),sum('Fixed'),sum('Ready_to_Test'),sum('Reopen'),sum('Closed'), sum('Rejected') 
from 
(
SELECT 

B.BG_USER_05 as Functionality, 
count(case when bg_status= 'New' then 1 end) as 'New', 
count(case when bg_status= 'Open' then 1 end) as 'Open', 
count(case when bg_status= 'Assigned' then 1 end) as 'Assigned', 
count(case when bg_status= 'Fixed' then 1 end) as 'Fixed', 
count(case when bg_status= 'Ready to Test' then 1 end) as 'Ready_to_Test', 
count(case when bg_status= 'Reopen' then 1 end) as 'Reopen', 
count(case when bg_status= 'Closed' then 1 end) as 'Closed', 
count(case when bg_status= 'Rejected' then 1 end) as 'Rejected' 

FROM 
    BUG B, 
    RELEASES R 

WHERE 
    B.BG_DETECTED_IN_REL = R.REL_ID 

GROUP BY 
    B.BG_USER_05 

UNION 

SELECT 'UAT' AS Functionality, 
0   AS 'New', 
0   AS 'Open', 
0   AS 'Assigned', 
0   AS 'Fixed', 
0   AS 'Ready_to_Test', 
0   AS 'Reopen', 
0   AS 'Closed', 
0   AS 'Rejected' 
) 

group by Functionality