我是SQL Server新手并编写此查询:
SELECT ROW_NUMBER() over (ORDER BY TelNo ) as RowNum,
Telno
FROM [ClubEatc].[dbo].[GetOnlineBills]
where RowNum=1
当我运行该查询时,我收到此错误:
Msg 207,Level 16,State 1,Line 11
无效的列名称'RowNum'。
我该如何解决?
谢谢大家。
答案 0 :(得分:0)
以这种方式试试,
SELECT *
FROM ( SELECT ROW_NUMBER() over (ORDER BY TelNo ) as RowNum, Telno
FROM [ClubEatc].[dbo].[GetOnlineBills]
) AS tbl
WHERE RowNum=1
答案 1 :(得分:0)
您无法在同一select
语句中过滤排名函数结果。
使用以下脚本。
with cte_1
as
(
SELECT ROW_NUMBER() over (ORDER BY TelNo ) as RowNum,Telno FROM [ClubEatc].[dbo].[GetOnlineBills])
SELECT *
FROM cte_1
where RowNum=1
答案 2 :(得分:0)
您收到此错误是因为您无法在WHERE语句中使用计算列别名,或者甚至放置where ROW_NUMBER() over (ORDER BY TelNo ) = 1
因为它被禁止。
您需要使用CTE或子查询,只需使用TOP 1 WITH TIES
按ROW_NUMBER()
排序:
SELECT TOP 1 WITH TIES Telno
FROM [ClubEatc].[dbo].[GetOnlineBills]
ORDER BY ROW_NUMBER() over (ORDER BY TelNo)