加入两个查询后缺少值

时间:2016-04-14 12:36:29

标签: sql-server sql-server-2008 join null jointable

我有疑问:

select 
       coalesce(t1.L1, t4.L2) as L1, 
       coalesce(t1.L2, t4.L2) as L2, 
       coalesce(t1.S, t4.S) as S,
       coalesce(t1.Q, t4.Q) as Q,
       coalesce(t1.Value, 0) as Value, 
       coalesce(t4.Prev_Value, 0) as Prev_Value
from (
  select L1, L2, S, Q, sum(value) as Value
  from table1
  group by L1, L2, S, Q
  ) as t1
left join
(
  select L1, L2, S, Q, sum(value) as Prev_Value
  from table1
  group by L1, L2, S, Q
) as t4 on
t1.L1 = t4.L1 and
t1.L2 = t4.L2 and
t1.Q = cast((cast(left(t4.Q,4) as numeric) +1) as varchar)+right(t4.Q,2) and
t1.S = t4.S

我现在得到了结果: enter image description here

我知道在2015财年第1季度我没有价值C(对于第S1列)。 但是如何反正显示缺失值? enter image description here

FULL OUTER JOIN的结果: enter image description here

2 个答案:

答案 0 :(得分:1)

使用FULL OUTER JOIN,但包含一个WHERE子句,用于删除t4表中您不希望看到的行。

答案 1 :(得分:0)

也改变了

t1.Q = cast((cast(left(t4.Q,4) as numeric) +1) as varchar)+right(t4.Q,2)

t1.Q = 'FY'+cast((cast(substring(t4.Q,3,6) as numeric) +1) as varchar)+right(t4.Q,2)