理論上,我希望基本上創建兩個具有相同列的獨立表格,並根據需要分別對它們分別排序,然後簡單地將其放在另一個表格下面並保留該順序。如何合併單獨的SQL查詢,每個將ORDER BY合併爲一個查詢?
我曾嘗試這樣做使用方法中的別處建議(見下文),如:
SELECT * FROM
(SELECT [company name], [appointment call back 1], [appointment call back 2], [appointment date 1], [appointment date 2] FROM Vantrack_Tulsa WHERE [appointment call back 1] BETWEEN '6/1/2016' AND '6/1/2017'
OR [appointment call back 2] BETWEEN '6/1/2016' AND '6/1/2017'
ORDER BY [company name] ASC) t
UNION ALL
SELECT * FROM
(SELECT [company name], [appointment call back 1], [appointment call back 2], [appointment date 1], [appointment date 2] FROM Vantrack_Tulsa WHERE [appointment date 1] BETWEEN '6/1/2016' AND '6/1/2017'
OR [appointment date 2] BETWEEN '6/1/2016' AND '6/1/2017'
ORDER BY [company name] ASC) s
,但我得到:
Msg 1033, Level 15, State 1, Line 8
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Msg 1033, Level 15, State 1, Line 13
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
我也試着這樣說:
WITH x as
(SELECT [company name], [appointment call back 1], [appointment call back 2], [appointment date 1], [appointment date 2] FROM Vantrack_Tulsa WHERE [appointment call back 1] BETWEEN '6/1/2016' AND '6/1/2017'
OR [appointment call back 2] BETWEEN '6/1/2016' AND '6/1/2017'
ORDER BY [company name] ASC),
y as
(SELECT [company name], [appointment call back 1], [appointment call back 2], [appointment date 1], [appointment date 2] FROM Vantrack_Tulsa WHERE [appointment date 1] BETWEEN '6/1/2016' AND '6/1/2017'
OR [appointment date 2] BETWEEN '6/1/2016' AND '6/1/2017'
ORDER BY [company name] ASC)
SELECT * FROM x UNION ALL SELECT * FROM y
但我得到:
Msg 1033, Level 15, State 1, Line 8
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword 'ORDER'.
也許出於同樣的原因。
我看到這個問題已經被問到,但假設的解決方案要麼從未真正起作用,要麼不再起作用。
一些所謂的答案我經過
- How to combine two SQL queries with different ORDER BY clauses
- Using different order by with union
- SQL Server query with union and different order by to each section?
有我俯瞰的東西嗎?任何方式來做到這一點?
你說「表」,但你的錯誤信息意味着非常不同的東西。那麼 - 你的目標是什麼** EXACTLY **?視圖像表格一樣沒有固有的順序 - 您必須使用順序依據子句來提供順序(一般而言,這在視圖中不起作用)。 – SMor