This question is in relation to a previous question I've asked ... see "SQL Server 2005 How to order a recordset when using the LIKE operator".
The following works ...
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;
But what I really want to do is this, as I'm using the server to page through records ...
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;
I'm getting an error " Invalid column name 'rnk' ".
Does anyone have any ideas on how to solve this problem?
Many thanks,
Mark
The problem is in the common table expression (CTE) definition. You can't reference rnk
in the same SELECT clause where the column alias is defined. You can try this:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.