使用带有Row_Number()的COALESCE字段时列名无效

时间:2014-04-07 17:13:05

标签: sql sql-server-2008

我有这个查询适用于SQL Server 2008:

 SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName) [CalculatedEmployeeName] 
 FROM Emp_General 
 ORDER BY [CalculatedEmployeeName] ASC

(请注意,它是按CalculatedEmployeeName字段排序而不是抱怨)

当我按如下方式添加Row_Number字段时:

 SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName) [CalculatedEmployeeName]
 , Row_Number() Over (Order BY [CalculatedEmployeeName] ASC) RecordNumber
 FROM Emp_General
 ORDER BY [CalculatedEmployeeName] ASC

我收到错误:

Invalid column name 'CalculatedEmployeeName'.

有关为什么抱怨的任何想法?

请注意,我已尝试使用

row_number() OVER (ORDER BY (SELECT 0))

row_number() over (order by @@rowcount)

如下所述:

SQL Row_Number() function in Where Clause without ORDER BY?

但是他们没有按正确的顺序返回row_number。

5 个答案:

答案 0 :(得分:1)

试试这个

 ;with cte as
    (
    SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName) [CalculatedEmployeeName]
     FROM Emp_General
    )

    select *,Row_Number() Over (Order BY [CalculatedEmployeeName] ASC)  as RecordNumber from cte ORDER BY [CalculatedEmployeeName] ASC

答案 1 :(得分:0)

更改为:

SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName) [CalculatedEmployeeName]
     , Row_Number() Over (Order BY COALESCE(LastName + ', ' + FirstName, LastName, FirstName) ASC) RecordNumber
FROM Emp_General
ORDER BY [CalculatedEmployeeName] ASC

无法引用SELECT

中的派生列

答案 2 :(得分:0)

您无法使用在此查询中指定的名称,您必须使用全名:

SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName)  [CalculatedEmployeeName], 
Row_Number() Over (ORDER BY COALESCE(LastName + ', ' + FirstName, LastName, FirstName) ASC) RecordNumber
FROM Emp_General

或者,您也可以使用以下内容:

;with Data as (
    SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName) [CalculatedEmployeeName] 
    FROM Emp_General 

) SELECT CalculatedEmployeeName, Row_Number() 
      OVER(Order By CalculatedEmployeeName Asc) RecordNumber FROM Data 
ORDER BY [CalculatedEmployeeName] ASC

答案 3 :(得分:0)

您可以使用子查询来访问派生列

SELECT Z.[CalculatedEmployeeName],
       Row_Number() Over (Order BY Z.[CalculatedEmployeeName] ASC) RecordNumber
FROM 
(
 SELECT COALESCE(LastName + ', ' + FirstName, LastName, FirstName) [CalculatedEmployeeName] 
 FROM Emp_General 
) Z
 ORDER BY Z.[CalculatedEmployeeName] ASC

答案 4 :(得分:0)

此行为的原因是ORDER BY是SQL Server计算顺序中的最后一个。 SQL操作顺序是: FROM条款
WHERE子句
GROUP BY条款
HAVING子句
SELECT子句
ORDER BY子句

(来自此处的数据:http://www.bennadel.com/blog/70-sql-query-order-of-operations.htm

因此SQL可以通过此计算列进行排序,但它不能对其执行ROW_NUMBER。 如上所述,您可以使用cte或明确写入计算。