以下是2个查询 -
select * --1
from Employee --2
where HireDate < '7/1/2001' --3
order by HireDate --4
--5 gap
select top(2) * --6
from Employee --7
where HireDate >= '7/1/2001' --8
order by HireDate --9
我想对他们做一个UNION。当我将UNION置于5时,为什么会出现错误?
当我删除4并将UNION放入5时,我得到一个结果,但不同于我单独执行两个查询时的结果。你能告诉我为什么会这样吗?
为了使这项工作正常,我必须删除4,制作两个查询的派生表,在9之后放4,然后执行两个派生表的UNION。
答案 0 :(得分:2)
删除ORDER BY
之前的UNION
。 (它会导致语法错误)
select *
from Employee
where HireDate < '7/1/2001'
UNION
select top(2) *
from Employee
where HireDate >= '7/1/2001'
order by HireDate
ORDER BY
条款发生在UNION
答案 1 :(得分:1)
This will help you I guess for your question
Combining ORDER BY AND UNION in SQL Server
select first.Id, first.Name
from (
select top 1 *
from Locations
order by Id) first
union all
select last.Id, last.Name
from (
select top 1 *
from Locations
order by Id desc) last