理论上,我希望基本上创建两个具有相同列的独立表格,并根据需要分别对它们分别排序,然后简单地将其放在另一个表格下面并保留该顺序。如何合并单独的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