2013-03-04 89 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