Over(Partition by)列未被识别。列无效

时间:2013-11-22 18:38:06

标签: sql sql-server

当我执行以下查询时:

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,删除"" ....似乎没有任何效果。它只是不会识别该列。

2 个答案:

答案 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):

  
      
  1. FROM
  2.   
  3. ON
  4.   
  5. JOIN
  6.   
  7. WHERE
  8.   
  9. GROUP BY
  10.   
  11. WITH CUBE或WITH ROLLUP
  12.   
  13. HAVING
  14.   
  15. 选择
  16.   
  17. DISTINCT
  18.   
  19. ORDER BY
  20.   
  21. TOP
  22.   

答案 1 :(得分:5)

另一种方法是使用CTE:

;WITH x AS (SELECT MH.whatever, ROW_NUMBER() ... AS NewRow FROM dbo.table)
SELECT * FROM x WHERE NewRow = 1;