如何使用sub select中的值

时间:2016-03-11 14:44:09

标签: sql sql-server subquery repeat correlated-subquery

我有一个选择:

select
b.[FiscalPeriod],
b.[Column2],b.[Current_Value],
(
    select TOP 1 [Column3] from [table1] b2 
    where month(b.ReportingPeriod) = month(DATEADD(month,1,b2.ReportingPeriod))
      AND YEAR(b.ReportingPeriod) = YEAR(DATEADD(month,1,b2.ReportingPeriod))
      AND b.id = b2.id
) as PREV_VALUE 
FROM [table1] b

现在我正在做:(b.[Current_Value]-PREV_VALUE) as difference

但我收到了错误:

  

列名称无效' PREV_VALUE'

我知道而不是PREV_VALUE,我可以再次选择。 但是如何避免重复选择?

2 个答案:

答案 0 :(得分:3)

您无法访问定义它的表别名。在您的情况下,最佳解决方案可能是outer apply

select b.[FiscalPeriod], b.[Column2],b.[Current_Value], bb.PREV_VALUE
FROM [table1] b OUTER APPLY
     (select TOP 1 [Column3] as PREV_VALUE
      from [table1] b2 
      where month(b.ReportingPeriod) = month(DATEADD(month,1,b2.ReportingPeriod)) AND
            YEAR(b.ReportingPeriod) = YEAR(DATEADD(month,1,b2.ReportingPeriod)) AND
            b.id = b2.id
      order by ???
     ) bb

然后,您可以在SELECT

中多次访问该值

注意:使用TOP时,您应该使用ORDER BY,因此您应该填写???

答案 1 :(得分:1)

您可以将查询转换为派生表或CTE。然后你可以像列一​​样处理别名:

SELECT *, (Current_Value-PREV_VALUE) AS difference
FROM (
  Your current query
) q