如何通过在SQL中使用联合所有的命令?

我试过下面给出的SQL查询:

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

它导致以下错误:

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

我需要在工会中使用秩序。 我如何做到这一点?

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

但是如果您想要从结果列表顶部的Table_A所有logging,则可以添加可用于sorting的用户定义值,

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

你并不需要有括号。 你可以直接sorting:

 SELECT *, 1 AS RN FROM TABLE_A UNION ALL SELECT *, 2 AS RN FROM TABLE_B ORDER BY RN, COLUMN_1 

不是一个OP的直接反应,但我想我会在这里吉米特别是在回应OP的错误消息,这指向另一个方向。

所有这些答案指的是一旦logging集已经被检索并且你整理了整个 ORDER BY。

如果你想独立地对UNION的每个部分进行ORDER BY,并且仍然让它们在同一个SELECT中“join”?

 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是一个任意数字。 使用一个足够大的数字来捕获所有你需要的数据。

 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