如何在sql中使用union all命令?

时间:2013-03-18 05:18:11

标签: sql sql-server

我尝试了下面给出的sql查询:

SELECT * FROM (SELECT * 
FROM TABLE_A ORDER BY COLUMN_1)DUMMY_TABLE
UNION ALL 
SELECT * FROM TABLE_B 

导致以下错误:

  

ORDER BY子句在视图,内联函数中派生无效   表,子查询和公用表表达式,除非TOP或FOR   还指定了XML。

我需要在联盟中使用order by all。我该如何做到这一点?

7 个答案:

答案 0 :(得分:87)

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

但如果您希望在结果列表的顶部包含Table_A的所有记录,则可以添加可用于订购的用户定义值,

SELECT  * 
FROM 
        (
            SELECT *, 1 sortby FROM TABLE_A 
            UNION ALL 
            SELECT *, 2 sortby FROM TABLE_B
        ) dum
ORDER   BY sortby 

答案 1 :(得分:30)

你真的不需要括号。你可以直接排序:

CustomEditText

答案 2 :(得分:16)

不是OP的直接反应,但我想我会在这里回应OP的ERROR消息,这可能会让你完全指向另一个方向!

一旦检索到记录集并对您进行排序,所有这些答案都指的是整体 ORDER BY。

如果您想独立地对UNION的每个部分进行排序,并且仍然让他们加入"在同一个SELECT?

SELECT pass1.* FROM 
 (SELECT TOP 1000 tblA.ID, tblA.CustomerName 
  FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL 
SELECT pass2.* FROM 
  (SELECT TOP 1000 tblB.ID, tblB.CustomerName 
   FROM TABLE_B AS tblB ORDER BY 2) AS pass2

注意TOP 1000是一个任意数字。使用足够大的数字来捕获所需的所有数据。

答案 3 :(得分:0)

有时候你需要做这样的事情:

根据排序从表 1 中提取前 5 个
表 2 中的底部 5 个基于另一种排序
并将它们结合在一起。

解决方案

select * from (
-- top 5 records
select top 5 col1, col2, col3 
from table1 
group by col1, col2
order by col3 desc ) z 

union all

select * from (
-- bottom 5 records 
select top 5 col1, col2, col3 
from table2 
group by col1, col2
order by col3 ) z 

这是我能够绕过错误并且对我来说工作正常的唯一方法。

答案 4 :(得分:0)

SELECT * FROM (SELECT * FROM TABLE_A ORDER BY COLUMN_1)DUMMY_TABLE 联合所有 SELECT * FROM TABLE_B 按 2 排序;

2 是此处的列号.. 在 Oracle SQL 中,您可以使用列号对数据进行排序

答案 5 :(得分:-2)

select CONCAT(Name, '(',substr(occupation, 1, 1), ')') AS f1
from OCCUPATIONS
union
select temp.str AS f1 from 
(select count(occupation) AS counts, occupation, concat('There are a total of ' ,count(occupation) ,' ', lower(occupation),'s.') As str  from OCCUPATIONS group by occupation order by counts ASC, occupation ASC
 ) As temp
 order by f1

答案 6 :(得分:-5)

Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation 
Union All 
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock) 
where DesignationId=@Designation 
order by NotificationId desc