Search code examples
sqlsql-serversubqueryrepeatcorrelated-subquery

How to use value from sub select


I have one select:

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

Now I'm doing: (b.[Current_Value]-PREV_VALUE) as difference

but I got error:

Invalid column name 'PREV_VALUE'

I know that instead of PREV_VALUE, once again I can put sub select. But how to avoid repeat the select?


Solution

  • You cannot access a table alias where it is defined. In your case, the best solution is probably 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
    

    Then you can access the value more than once in the SELECT.

    Note: When using TOP you should be using ORDER BY, so you should fill in the ???.