如何将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)
答案 0 :(得分:1)
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