连接问题在我的查询中,如何将空值填充为零

时间:2013-03-08 22:39:20

标签: sql

我的查询是获取过去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 n sql

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我不确定查询是如何工作的,您将year两次别名z。但是,假设这不是问题,您可以将LEFT OUTER JOIN更改为RIGHT OUTER JOIN。或者,如果您不喜欢RIGHT OUTER JOIN,请重新编写SELECT,以便FROM子句引用year表。