2013-03-08 51 views
0

我的查詢是獲取過去5周的數據。問題與連接在我的查詢,如何填充空值爲零

select z.week, 
sum(case when i.severity=1 then 1 else 0 end) as 1 
sum(case when i.severity=2 then 1 else 0 end) as 2 
sum(case when i.severity=3 then 1 else 0 end) as 3 
sum(case when i.severity=4 then 1 else 0 end) as 4 
from instance as i 
and left outer join year as z on convert(varchar(10),z.date,101)=convert(varchar(10),i.created,101) 
and left outer join year as z on convert(varchar(10),z.date,101)=convert(varchar(10),i.closed,101) 
where i.group in '%Teams%' 
and z.year=2013 
and z.week<=6 and z.week>1 

這裏有幾個星期在我的實例表中,甚至沒有一行。所以這裏我沒有得到空或零...而是整個行並沒有提示。

我目前的輸出。

week | 1 | 2 | 3 | 4 
--------------------- 
2 | 0 | 1 | 8 | 5 
3 | 2 | 3 | 4 | 9 
5 | 1 | 0 | 0 | 0 

,但我需要像下面的輸出...

week | 1 | 2 | 3 | 4 
--------------------- 
2 | 0 | 1 | 8 | 5 
3 | 2 | 3 | 4 | 9 
4 | 0 | 0 | 0 | 0 
5 | 1 | 0 | 0 | 0 
6 | 0 | 0 | 0 | 0 

如何獲得所需的outputiñSQL

+0

你使用的是什麼風格的sql? – 2013-03-08 22:40:18

+0

使用左連接而不是左外連接 – Kyra 2013-03-08 22:42:14

+0

@Kyra都相同 – 2013-03-08 22:44:56

回答

1

試試這個

select z.week, 
sum(case when i.severity=1 then 1 else 0 end) as 1 
sum(case when i.severity=2 then 1 else 0 end) as 2 
sum(case when i.severity=3 then 1 else 0 end) as 3 
sum(case when i.severity=4 then 1 else 0 end) as 4 
from year as z 
left outer join instance as i on 
convert(varchar(10),z.date,101)=convert(varchar(10),i.created,101) 
and convert(varchar(10),z.date,101)=convert(varchar(10),i.closed,101) 
where (i.group is null or i.group in '%Teams%') 
and z.year=2013 
and z.week<=6 and z.week>1 
+0

我試過了,但沒有運氣。 在我的情況下,在實例中不能確定數據是否存在。像那裏不會有任何i.created和i.closed。 – nitish 2013-03-08 23:11:43

+0

@nitish,當你使用左外連接時,即使沒有i.created的數據,i.closed也會從年表中返回行。你能發佈一些來自年/實例表的示例數據嗎? – 2013-03-09 00:31:34

1

我不知道查詢是如何工作的,您在別名year兩次到z。但是,假設這不是問題,您可以將LEFT OUTER JOIN更改爲RIGHT OUTER JOIN。或者,如果您不喜歡RIGHT OUTER JOIN,請重新選擇SELECT,以便FROM子句引用year表。