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

如何获得所需的输出in sql

4

2 回答 2

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
于 2013-03-08T22:50:40.027 回答
1

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

于 2013-03-08T22:51:23.340 回答