我编写了一个SQL Server查询,它返回几个select语句的并集。查询返回我期望的数据。
但它正在做的一个意想不到的事情是它按字母顺序对数据进行排序。但是,我想要的是第一个表的数据应该出现在顶部,第二个表的数据应该出现在第二个,依此类推。
有人可以帮我吗?
select employeename from employeetable where employeename like 'vik%'
union
select employeename from employeetable where employeename like '% vik%'
union
select employeename from EmployeeTable where employeename like '%vik%' and
employeename not like 'vik%' and
employeename not like '% vik%'
答案 0 :(得分:2)
您可以在不union
的情况下执行此操作:
select employeename
from employeetable
where employeename like '%vik%'
order by (case when employeename like 'vik%' then 1
when employeename like '% vik%' then 2
else 3
end);
如果您可以在employeename
中复制employeetable
,则可以使用group by
删除重复项:
select employeename
from employeetable
where employeename like '%vik%'
group by employeename
order by (case when employeename like 'vik%' then 1
when employeename like '% vik%' then 2
else 3
end);
答案 1 :(得分:2)
为表序列添加一列
select employeename, 1 as my_order from employeetable where employeename like 'vik%'
union
select employeename, 2 from employeetable where employeename like '% vik%'
union
select employeename, 3 from EmployeeTable where employeename like '%vik%' and employeename not like 'vik%' and employeename not like '% vik%'
order by my_order asc, empleemployeename asc;
答案 2 :(得分:0)
select employeename, a as _order from employeetable where employeename like 'vik%'
union
select employeename, b as _order from employeetable where employeename like '% vik%'
union
select employeename, c as _order from EmployeeTable where employeename like '%vik%' and employeename not like 'vik%' and employeename not like '% vik%'
order by my_order asc, empleemployeename asc;
答案 3 :(得分:0)
select 1 s,employeename from employeetable where employeename like 'vik%'
union
select 2 s, semployeename from employeetable where employeename like '%vik%'
union
select 3 s,employeename from EmployeeTable where employeename like '%vik%' and employeename not like 'vik%' and employeename not like '% vik%'
order by s;
你的3个表中的进一步排序顺序是未定义的,如果没有指定,可能会变成任何东西