当我执行以下查询时:
SELECT
MH.MemberKey,
ROW_NUMBER() OVER(PARTITION BY MH.MemberKey ORDER BY MH.MemberKey ASC) AS "NewRow",
MH.FirstName,
MH.LastName,
MH.BirthDate,
MH.AddressLine1,
MH.AddressLine2,
MH.AddressLine3,
MH.City AS MemberCity,
MH.StateCode AS MemberState,
MH.ZipCode AS MemberZip
FROM MembershipHistory MH
WHERE NewRow = 1;
我收到以下错误:
Msg 207,Level 16,State 1,Line 36 列名称“NewRow”无效。
我尝试保留AS
,删除AS
,删除""
....似乎没有任何效果。它只是不会识别该列。
答案 0 :(得分:9)
SELECT中的row_number
函数的评估是在应用WHERE子句之后完成的,因此无法识别别名,您可以使用子查询来获得结果:
select
MH.MemberKey,
NewRow,
MH.FirstName,
MH.LastName,
MH.BirthDate,
MH.AddressLine1,
MH.AddressLine2,
MH.AddressLine3,
MH.City AS MemberCity,
MH.StateCode AS MemberState,
MH.ZipCode AS MemberZip
from
(
SELECT
MH.MemberKey,
ROW_NUMBER() OVER(PARTITION BY MH.MemberKey ORDER BY MH.MemberKey ASC) AS NewRow,
MH.FirstName,
MH.LastName,
MH.BirthDate,
MH.AddressLine1,
MH.AddressLine2,
MH.AddressLine3,
MH.City AS MemberCity,
MH.StateCode AS MemberState,
MH.ZipCode AS MemberZip
FROM MembershipHistory MH
) MH
WHERE NewRow = 1;
在SQL Server中,SELECT语句的逻辑处理顺序是(来自MSDN Docs):
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE或WITH ROLLUP
- HAVING
- 选择
- DISTINCT
- ORDER BY
- TOP
醇>
答案 1 :(得分:5)
另一种方法是使用CTE:
;WITH x AS (SELECT MH.whatever, ROW_NUMBER() ... AS NewRow FROM dbo.table)
SELECT * FROM x WHERE NewRow = 1;