如何使用ORDER BY CHARINDEX()和UNION?

时间:2015-07-17 06:14:29

标签: sql sql-server

如何将ORDER BY CHARINDEX()UNION一起使用? 我想要的是:

select  Id,Name from A where Name like '%Raspberry%' 
Union
select  Id,Name from B where Name like '%Raspberry%' 
order by CHARINDEX('Raspberry',Name)

2 个答案:

答案 0 :(得分:1)

Common Table Expression会帮助您:

with cte as (
select  Id,Name, CHARINDEX('Raspberry', Name) ci from #t1 where Name like '%Raspberry%' 
Union
select  Id,Name, CHARINDEX('Raspberry', Name) ci from #t2 where Name like '%Raspberry%' 
) 
select  Id, Name
from cte
order by ci

<强> SQL FIDDLE

答案 1 :(得分:0)

如前所述,问题是如果使用UNION,则必须按顺序选择列。试试这个。

select  Id,Name,CHARINDEX('Raspberry',Name) as order_col 
from A 
where Name like '%Raspberry%' 
Union
select  Id,Name,CHARINDEX('Raspberry',Name) as order_col 
from B 
where Name like '%Raspberry%' 
order by order_col