使用列别名的SQL Server分页查询

时间:2014-10-17 11:09:19

标签: sql sql-server

我正在尝试创建一个查询,然后我可以将其用于分页系统,这是查询的原样

SELECT   
   SLCustomerAccountID, 
   CustomerAccountNumber, 
   CustomerAccountName, 
   (MainTelephoneAreaCode +  MainTelephoneSubscriberNumber) AS PhoneNumber,
   Row_Number() over (order by CustomerAccountName) as RowIndex 
FROM         
   SLCustomerAccount
WHERE   
   CustomerAccountName LIKE '%green%' 
   AND RowIndex BETWEEN 10 AND 30
ORDER BY 
   CustomerAccountName

此查询错误

  

列名称无效' RowIndex'。

因为我正在尝试使用别名,但我不确定设置此方法的正确方法,因此我可以使用列RowIndex

中的数据

以下是查询在没有where子句

的情况下返回的内容
   ID1      ID2      NAME    Number  Row number
__________________________________________
| 12374927| 00010014|Some name| ******| 1|
| 51744   | 6631    |Same name| ******| 2|

2 个答案:

答案 0 :(得分:2)

您无法在WHERE中使用别名(仅限于ORDER BY)。但您可以从CTE访问它:

WITH CTE AS
(

    SELECT SLCustomerAccountID, 
           CustomerAccountNumber, 
           CustomerAccountName, 
           (MainTelephoneAreaCode +  MainTelephoneSubscriberNumber) AS PhoneNumber,
           Row_Number() over (order by CustomerAccountName) as RowIndex 
    FROM   SLCustomerAccount
    Where CustomerAccountName LIKE '%green%' 
)
SELECT SLCustomerAccountID, 
        CustomerAccountNumber, 
        CustomerAccountName, 
        (MainTelephoneAreaCode +  MainTelephoneSubscriberNumber) AS PhoneNumber
FROM CTE
WHERE RowIndex Between 10 AND 30
ORDER BY CustomerAccountName

答案 1 :(得分:0)

查询在SQLSERVER中按以下顺序执行 -

1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE or WITH ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP

所以在这种情况下, WHERE 子句将在 SELECT 子句之前执行。因此,别名列名称在WHERE子句中不可用。