列就位时出现无效的列名错误

时间:2019-09-23 17:12:01

标签: sql sql-server

我正在尝试选择结束日期在范围内的行。在我的dbo.subscription表中,我有startdate和enddate列。当我使用startdate时,查询会运行,但是当我使用enddate时,它说列名无效。

我尝试在结束日期前后使用''或“” [],也尝试将列的全名写出(dbo.subscription.enddate),但似乎没有什么不同。

;WITH cte 
     AS (SELECT Membershipnumber as Id
               Row_number() 
                  OVER ( 
                    partition BY membershipnumber 
                    ORDER BY subscription.enddate DESC) AS rownumber 
         FROM   [dbo].[userprofile] 
                INNER JOIN dbo.subscription 
                        ON userprofile.id = subscription.userprofileid 
                INNER JOIN dbo.subscriptiontype 
                        ON subscriptiontype.id = subscription.subscriptiontypeid

        ) 
SELECT * 
FROM   cte 
WHERE  rownumber = 1 and enddate between'2014-12-31' and '2018-12-31'
order by Id

错误消息:

Msg 207, Level 16, State 1, Line 21
Invalid column name 'enddate'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'enddate'.

1 个答案:

答案 0 :(得分:5)

您最终的SELECT是SELECT FROM cte

cte仅定义两列:IdRowNumber

enddate未在cte中定义。