2013-03-04 90 views
0

我有問題與我的查詢。查詢不填充空colomns

此查詢提取我最近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 '%Tools%' 
and z.year=2013 
and z.week<=6 and z.week>1 

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

我目前的輸出。

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

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

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

我的問題爲t如何獲得在實例表不存在行的零.. 這個親切指導。

回答

0

看起來你需要一個正確的連接而不是左邊。如果您希望表達式的第1列中存在一些數據,但它涉及到聯接表達式的右側,則需要將它包含在右側聯接中,或者重寫您的from子句以使其處於第一個狀態。

編輯:下面是一些簡單的例子一個簡單的例子加入:

declare @Z table (dt date, value int); 

insert into @Z values ('3-1-2013', 10),('3-4-2013',20); 

declare @Y table (dt date, value int); 

insert into @Y values ('3-1-2013', 5),('3-3-2013', 30); 

select * from @Z -- @Z table as is 
select * from @Y -- @Y table as is 

select * 
from @Z z 
    inner join @Y y on z.dt = y.dt -- I only get the values that they both exist on 

select * 
from @Z z 
    left outer join @Y y on z.dt = y.dt -- I get the values of @Z table regardless if @Y exists or not 

select * 
from @Z z 
    right outer join @Y y on z.dt = y.dt -- I get the values of @Y table regardless if @Z exists or not, I flipped my logic 

select * 
from @Z z 
    full outer join @Y y on z.dt = y.dt -- I get all the values of @Z table and @Y regardless of matching rules 
+0

我無法得到空魚卵在我的輸出。 – nitish 2013-03-04 20:20:11

+0

我無法在我的outpur中得到空colomns。在此指導我 – nitish 2013-03-04 20:20:58

+0

您是否在所有匹配的表上都有空值?沒有數據在任何位置?如果是這種情況,我會創建第三個表或包含手動值的對象。你不能加入那些不存在的東西。 – djangojazz 2013-03-04 20:22:39