我有查询,工作正常:
select t1.[Fiscal Year],
t1.[Level1], t1.[Level2], t1.[colE],t1.[colF],
t1.Value,t2.Value [previous_value]
from
( select [Fiscal Year],[Level1],[Level2],[colE],[colF],sum([CA Service Bookings Net]) value
from [table1]
group by [Fiscal Year],[Level1],[Level2],[colE],[colF]
)t1
left JOIN
(
select [Fiscal Year],[Level1],[Level2],[colE],[colF],sum([CA Service Bookings Net]) value
from [table1]
group by [Fiscal Year],[Level1],[Level2],[colE],[colF]
)t2
ON t1.[Fiscal Year] = t2.[Fiscal Year]+1 and
t1.[Level1] = t2.[Level1] and
t1.[Level2] = t2.[Level2] and
t1.[colE] = t2.[colE] and
t1.[colF] = t2.[colF]
当我想添加更多列(colE,colF,colG ...)时,它没问题。
但是当我尝试添加列时: [QuarterID] 包含的值为:2015Q1,2015Q2,2015Q3,2015Q4,2016Q1 ......
t2.Value [previous_value]返回空值。你知道什么是理由吗?
这是带有[QuarterID]的代码:
select t1.[Fiscal Year],t1.[QuarterID],
t1.[Level1], t1.[Level2], t1.[colE],t1.[colF],
t1.Value,t2.Value [previous_value]
from
( select [Fiscal Year],[QuarterID],[Level1],[Level2],[colE],[colF],sum([CA Service Bookings Net]) value
from [table1]
group by [Fiscal Year],[QuarterID][Level1],[Level2],[colE],[colF]
)t1
left JOIN
(
select [Fiscal Year],[QuarterID],[Level1],[Level2],[colE],[colF],sum([CA Service Bookings Net]) value
from [table1]
group by [Fiscal Year],[QuarterID],[Level1],[Level2],[colE],[colF]
)t2
ON t1.[Fiscal Year] = t2.[Fiscal Year]+1 and
t1.[Level1] = t2.[Level1] and
t1.[Level2] = t2.[Level2] and
t1.[colE] = t2.[colE] and
t1.[colF] = t2.[colF] and
t1.[QuarterID] = t2.[QuarterID]
答案 0 :(得分:0)
我能想象你得到NULLS的唯一方法就是你要么没有正确地将QuarterID添加到t1&的JOIN条件中。 t2,或者如果您希望在t2中找到QuarterID,但是那里没有。
您是否加入t1中的2015Q1
将加入t2中的2014Q1
?并且所有必需的quarterID都存在吗?
答案 1 :(得分:0)
刚做完并且工作得很完美:
t1.[Fiscal Quarter ID] = cast((cast(left(t2.[Fiscal Quarter ID],4) as numeric) +1) as varchar)+right(t2.[Fiscal Quarter ID],2)