SQL SELECT中的分页与ORDER BY基于CASE生成的列 - SQL

时间:2013-02-11 18:25:50

标签: sql-server-2008 pagination sql-order-by case

我正在使用MS SQL SERVER 2008,我创建了以下查询(简化);

SELECT DATE_A, DATE_B
CASE
WHEN DATEDIFF(day, DATE_A, GETDATE()) >= 1 THEN 1
WHEN DATEDIFF(day, DATE_B, GETDATE()) >= 1 AND DATEDIFF(day, DATE_A, GETDATE()) <1 THEN             2
ELSE 3
END AS sortPriority,
CASE
--deadline past
WHEN DATEDIFF(day, DATE_A, GETDATE()) >= 1 THEN DATE_A
--review only past
WHEN DATEDIFF(day, DATE_B, GETDATE()) >= 1 AND DATEDIFF(day, DATE_A()) <1 DATE_B
--anything else
ELSE DATE_B
END AS sortDate
FROM myTable
WHERE (DATEDIFF(day, DATE_A, GETDATE()) >=1 OR DATEDIFF(day, DATE_B, GETDATE()) >=1)
ORDER BY sortPriority, sortDate;

查询返回DATE_A或DATE_B比今天更早的行。行按sortPriority排序,然后按sortDate排序。

我现在需要为此查询添加分页,但是当我在ROW_NUMBER()函数的order by子句中使用sortPriority或sortDate列时,查询失败;

WITH sortedTable AS
(
SELECT DATE_A, DATE_B,
CASE
WHEN DATEDIFF(day, DATE_A, GETDATE()) >= 1 THEN 1
WHEN DATEDIFF(day, DATE_B, GETDATE()) >= 1 AND DATEDIFF(day, DATE_A, GETDATE()) <1 THEN 2
ELSE 3
END AS sortPriority,
CASE
--deadline past
WHEN DATEDIFF(day, DATE_A, GETDATE()) >= 1 THEN DATE_A
--review only past
WHEN DATEDIFF(day, DATE_B, GETDATE()) >= 1 AND DATEDIFF(day, DATE_A()) <1 DATE_B
--anything else
ELSE DATE_B
END AS sortDate,
ROW_NUMBER() OVER (sortPriority, sortDate) AS 'RowNumber'
FROM myTable
WHERE (DATEDIFF(day, DATE_A, GETDATE()) >=1 OR DATEDIFF(day, DATE_B, GETDATE()) >=1)
)
SELECT * 
FROM sortedTable 
WHERE RowNumber BETWEEN 10 AND 20;

我收到以下错误消息;

Msg 207, Level 16, State 1, Line 24
Invalid column name 'sortPriority'.
Msg 207, Level 16, State 1, Line 24
Invalid column name 'sortDate'.

行号是指我的示例代码的这一行;

ROW_NUMBER() OVER (sortPriority, sortDate) AS 'RowNumber'

我如何处理此问题并获得所需的结果(原始排序原封不动)

1 个答案:

答案 0 :(得分:2)

UNTESTED:

WITH sortedTable AS
(
    SELECT DATE_A, DATE_B, sortPriority, sortDate,
           ROW_NUMBER() OVER (sortPriority, sortDate) AS 'RowNumber'
      FROM
          (
            SELECT DATE_A, DATE_B,
                   CASE WHEN DATEDIFF(day, DATE_A, GETDATE()) >= 1 THEN 1
                        WHEN DATEDIFF(day, DATE_B, GETDATE()) >= 1 AND DATEDIFF(day, DATE_A, GETDATE()) <1 THEN 2
                        ELSE 3
                    END AS sortPriority,
                   CASE
                        --deadline past
                        WHEN DATEDIFF(day, DATE_A, GETDATE()) >= 1 THEN DATE_A
                        --review only past
                        WHEN DATEDIFF(day, DATE_B, GETDATE()) >= 1 AND DATEDIFF(day, DATE_A()) <1 DATE_B
                        --anything else
                        ELSE DATE_B
                    END AS sortDate
               FROM myTable
              WHERE (DATEDIFF(day, DATE_A, GETDATE()) >=1 OR DATEDIFF(day, DATE_B, GETDATE()) >=1)
          ) T
)
SELECT * 
FROM sortedTable 
WHERE RowNumber BETWEEN 10 AND 20;