ROW_NUMBER()OVER(ORDER BY ...)的SQL Server 2005问题

时间:2011-03-28 03:23:47

标签: sql sql-server-2005 tsql

此问题与我之前提出的问题有关...请参阅“SQL Server 2005如何在使用LIKE运算符时订购记录集”。

以下作品......

with xx as
(
select  case
    when mycol = 'finance' then 1
    when mycol like 'finance%' then 2
    when mycol like '%finance%' then 3
    end as rnk, 
    *
from    MyTable
where   mycol like '%finance%'
)

select * from xx 
order by xx.rnk, xx.mycol;

但我真正想做的是,因为我正在使用服务器来翻阅记录......

WITH xx AS
(
select  case
    when t.term = 'finance' then 1
    when t.term like 'finance%' then 2
    when t.term like '%finance%' then 3
    end as rnk, 
    *, 
    row_number() over (order by rnk, t.term) as rownumber
from    tblTerms t
where   t.term like '%finance%'
)

select * from xx 
where rownumber between 11 and 20 -- page #2
order by xx.rnk, xx.mycol;

我收到错误“无效的列名'rnk'”。

有没有人对如何解决这个问题有任何想法?

非常感谢,

标记

1 个答案:

答案 0 :(得分:1)

问题出在公用表表达式(CTE)定义中。您不能在定义列别名的同一SELECT子句中引用rnk。你可以试试这个:

WITH xx AS
(
select  case
    when t.term = 'finance' then 1
    when t.term like 'finance%' then 2
    when t.term like '%finance%' then 3
    end as rnk, 
    *
from    tblTerms t
where   t.term like '%finance%'
),

yy AS
(
SELECT *,
    row_number() over (order by rnk, term) as rownumber
FROM xx
)

select * from yy 
where rownumber between 11 and 20 -- page #2
order by yy.rnk, yy.mycol;