Row_Number函数中的Sql Server别名

时间:2015-06-04 17:32:32

标签: sql sql-server-2012 row-number

select tmp.id, tmp.portfolio,
   ROW_NUMBER() OVER(order by tmp.id DESC) AS RowNum 
from 
  (select r.portfolio, r.id
   from research r 
   where r.created_by = 'Adam Cohen'
 ) as tmp 
WHERE RowNum BETWEEN 5 AND 10;

我无法在where条件中引用RowNum,因为它显示无效的列名称' RowNum'。请帮助我使用正确的语法来获得结果。

修改 - 更改要求

SELECT * FROM 
( 
     select id, portfolio, 
     CASE WHEN l.posted_on IS NULL 
          THEN CONVERT(VARCHAR(40),l.created_on,120) 
          ELSE CONVERT(VARCHAR(40),l.posted_on,120) 
     END AS sort_by, 
     ROW_NUMBER() OVER(order by sort_by DESC) AS RowNum 
     from research 
     where created_by = 'Adam Cohen' 
) x 
WHERE x.RowNum BETWEEN 5 AND 10 

我尝试添加上述Row_Number功能,但我将sort_by视为无效列。

2 个答案:

答案 0 :(得分:3)

您需要将投影包装在派生表中,尽管您可以删除内部tmp表:

SELECT * FROM
(
    select id, portfolio,
       ROW_NUMBER() OVER(order by id DESC) AS RowNum 
    from 
       research
    where created_by = 'Adam Cohen'
) x
WHERE x.RowNum BETWEEN 5 AND 10

修改

请注意,如果您在最终选择中实际上不需要伪行号,那么从Sql 2012开始,在您的“数据页面”场景中,您将能够使用OFFSET FETCH来应用根本需要ROW_NUMBER()或派生表:

select id, portfolio
from research
where created_by = 'Adam Cohen'
order by id desc
offset 5 rows fetch next 6 rows only;

编辑#2,重新提出新要求

CASE WHEN l.posted_on IS NULL 
   THEN CONVERT(VARCHAR(40),l.created_on,120) 
   ELSE CONVERT(VARCHAR(40),l.posted_on,120) 
END AS sort_by

可以更简洁地表达为

CONVERT(VARCHAR(40), COALESCE(posted_on, created_on)) AS AS sort_by

但是,如果您仍然需要原始行号,则还要在窗口函数ORDER BYOVER)中使用此投影,为了干掉它,您将需要嵌套的派生表。但是,您仍然可以使用SQL 2012 OFFSET / FETCH NEXT进行分页:

SELECT *,
       ROW_NUMBER() OVER(order by sort_by DESC) AS RowNum 
FROM
(
    SELECT id, portfolio, CONVERT(VARCHAR(40), COALESCE(posted_on, created_on)) AS sort_by
    from research 
    where created_by = 'Adam Cohen' 
) y
ORDER BY id DESC
OFFSET 5 ROWS FETCH NEXT 6 ROWS ONLY;

答案 1 :(得分:2)

您需要将ROW_NUMBER嵌套在派生表中:

select tmp.id, tmp.portfolio, tmp.RowNum
from 
  (select r.portfolio, r.id,
      ROW_NUMBER() OVER(order by r.id DESC) AS RowNum 
   from research r 
   where r.created_by = 'Adam Cohen'
 ) as tmp 
WHERE RowNum BETWEEN 5 AND 10;