TSQL - UNION中的订单查询

时间:2016-11-04 22:28:30

标签: sql sql-server tsql union

我们说我有以下表格

表1

Name        | Date Created

John Doe    | 09-10-2016
Mike Smith  | 08-05-2016
Super Man   | 09-07-2016

表2

Name          Date_Created
Super Mario | 02-01-2016
James Bond  | 05-01-2016

表3

Name          Date_Created
Mega Man    | 12-25-2016
Batman Jr   | 12-05-2016

如果我想将所有这些表连接在一起,我会使用UNION

SELECT * FROM Table1
UNION
SELECT * FROM Table2
UNION
SELECT * FORM Table3

这会产生:

Name          Date_Created
John Doe    | 09-10-2016
Mike Smith  | 08-05-2016
Super Man   | 09-07-2016
Super Mario | 02-01-2016
James Bond  | 05-01-2016
Mega Man    | 12-25-2016
Batman Jr   | 12-05-2016

有没有办法在表2中订购查询仅由“创建日期”' DESC使得结果显示如下:

Name          Date_Created
John Doe    | 09-10-2016
Mike Smith  | 08-05-2016
Super Man   | 09-07-2016

James Bond  | 05-01-2016       <-- DESC May 01 2016 then Feb 01 2016
Super Mario | 02-01-2016

Mega Man    | 12-25-2016
Batman Jr   | 12-05-2016

2 个答案:

答案 0 :(得分:2)

  

如果我想将所有这些表连接在一起,我会使用UNION

错误。如果要将它们全部合并,则默认值应为UNION ALL。只有在想要消除重复项的开销时才使用UNION

第二个误解:您无法订购结果集的部分。除非明确包含ORDER BY,否则结果集(如表)表示无序集。所以,你可以订购整件产品而不是订购产品。

你可以把结果放在一起,并做一些时髦的订购:

SELECT t.*
FROM ((SELECT t1.*, 1 as which FROM Table1 t1
      ) UNION ALL
      (SELECT t2.*, 2 as which FROM Table2 t2
      ) UNION ALL
      (SELECT t3.*, 3 as which FROM Table3 t3
      )
     ) t
ORDER BY which,
         (CASE WHEN which = 1 THEN name END),
         (CASE WHEN which = 2 THEN date_created END) DESC,
         (CASE WHEN which = 3 THEN name END) DESC;

答案 1 :(得分:0)

以下是我对同样的答案

CREATE TABLE #Table1(Name varchar(20),DateCreated date)
CREATE TABLE #Table2(Name varchar(20),DateCreated date)
CREATE TABLE #Table3(Name varchar(20),DateCreated date)

INSERT INTO #Table1 VALUES('John Doe','09-10-2016'),
('Mike Smith','08-05-2016'),
('Super Man','09-07-2016')

INSERT INTO #Table2 VALUES ('Super Mario','02-01-2016'),
('James Bond','05-01-2016')

INSERT INTO #Table3 VALUES ('Mega Man','12-25-2016'),
('Batman Jr','12-05-2016')


--Using CTE
With cte(Name,DateCreated) as
(
SELECT TOP (SELECT COUNT(*) FROM #Table2) * FROM #Table2 ORDER BY DateCreated DESC
)
SELECT * FROM #Table1 UNION ALL
SELECT * FROM cte UNION ALL
SELECT * FROM #Table3

GO

--Using Subquery
SELECT * FROM #Table1 UNION ALL
SELECT  FROM (SELECT TOP (SELECT COUNT(*) FROM #Table2)  FROM #Table2 ORDER BY DateCreated DESC)a UNION ALL
SELECT * FROM #Table3