我在cte中使用列别名进行连接时遇到问题。与Invalid column name
一致的RowNumber2 >= (t1.RowNumber - 20)
任何人都有建议吗?感谢..
DECLARE @latestDate Date = dbo.LatestDateWithPricingVolCountOver4k()
;WITH AllSymbsAndDates AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY Symbol ORDER BY TradingDate) AS RowNumber,
Symbol, TradingDate
FROM tblSymbolsMain
CROSS JOIN tblTradingDays
WHERE TradingDate <= @latestDate
),
SymbsDatesGrouped AS
(
SELECT * FROM
(
SELECT
t1.Symbol, t1.TradingDate, t2.TradingDate AS TradingDate2, t1.RowNumber,
t2.RowNumber AS RowNumber2
FROM AllSymbsAndDates t1
JOIN AllSymbsAndDates t2 ON t1.Symbol = t2.Symbol
AND RowNumber2 >= (t1.RowNumber - 20)
) t
)
SELECT
Symbol, TradingDate, TradingDate2, RowNumber, RowNumber2
FROM
SymbsDatesGrouped
ORDER BY
Symbol, TradingDate, TradingDate2
答案 0 :(得分:0)
您无法在WHERE
或JOIN
子句中引用列别名 - 实际上,您可以在SELECT列表中引用别名的唯一子句位于ORDER BY
(或者在外部范围内,例如从子查询或CTE中选择。)
在这种情况下,解决方案非常简单。为什么不说:
AND t2.RowNumber >= (t1.RowNumber - 20)