0

我在使用列别名连接 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
4

1 回答 1

0

您不能在WHEREorJOIN子句中引用列别名 - 实际上,您可以从 SELECT 列表中引用别名的唯一子句是在ORDER BY(或在外部范围内,例如从子查询或 CTE 中选择)。

在这种情况下,解决方案非常简单。为什么不直接说:

 AND t2.RowNumber >= (t1.RowNumber - 20)

?

于 2012-04-24T20:36:24.627 回答