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 '%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

我的问题是如何为实例表中不存在的行获取零。请对此进行指导。

4

1 回答 1

0

看起来您需要右连接而不是左连接。如果您希望表达式的第 1 列中存在一些数据,但它涉及连接表达式的 RIGHT,则需要将其包含在右连接中或重写您的 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
于 2013-03-04T20:08:13.550 回答