如何使用 sub select 的值
How to use value from sub select
我有一个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
现在我在做:(b.[Current_Value]-PREV_VALUE) as difference
但我收到错误:
Invalid column name 'PREV_VALUE'
我知道我可以再次放置 sub select 而不是 PREV_VALUE
。
但是如何避免重复select?
您无法在定义别名的地方访问 table 别名。在你的情况下,最好的解决方案可能是 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
,所以要填写???
.
您可以将查询转换为派生的 table 或 CTE。然后你可以像列一样对待别名:
SELECT *, (Current_Value-PREV_VALUE) AS difference
FROM (
Your current query
) q
我有一个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
现在我在做:(b.[Current_Value]-PREV_VALUE) as difference
但我收到错误:
Invalid column name 'PREV_VALUE'
我知道我可以再次放置 sub select 而不是 PREV_VALUE
。
但是如何避免重复select?
您无法在定义别名的地方访问 table 别名。在你的情况下,最好的解决方案可能是 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
,所以要填写???
.
您可以将查询转换为派生的 table 或 CTE。然后你可以像列一样对待别名:
SELECT *, (Current_Value-PREV_VALUE) AS difference
FROM (
Your current query
) q