table1
table2
和table3
有不同的列,但都有一個OrderDate
列。我想從所有3個表中獲得一組結果集,並且我希望最終結果集按OrderDate
排序。(SQL)連接表並訂購最終結果
(select * from table1 LEFT join table2 on 0=1 LEFT join table3 on 0=1
where somedate <= table1.orderdate)
union all
(select * from table1 RIGHT join table2 on 0=1 LEFT join table3 on 0=1
where somedate <= table2.orderdate)
union all
(select * from table1 RIGHT join table2 on 0=1 RIGHT join table3 on 0=1
where somedate <= table3.orderdate)
這工作,但我想這個結果設置爲orderdate
進行排序,所以我補充一下:
order by case when table1.orderdate is not null then table1.orderdate
when table2.orderdate is not null then table2.orderdate
else table3.orderdate end
SQL Server返回錯誤「ORDER BY項目必須出現在選擇列表中,如果語句包含一個UNION,INTERSECT或EXCEPT操作符。「
如果我更換
select *
通過
select *, table1.orderdate, table2.orderdate, table3.orderdate
我得到同樣的錯誤。
咦?謝謝。
SQL Server引發錯誤,指出'A'列多次指定'ID'列。但即使這是用別名解決的,你是否想使用table1,table2或table3的orderdate?這就是問題所在,在結果集的任意一行中,3列中的2列table1.orderdate,table2.orderdate,table3.orderdate爲null,因爲這是外連接。我想根據非空值的結果集對結果集進行排序... – SemMike
您可以使用where子句並指定:其中A.orderDate不爲空。順便說一句 – Egalitarian
執行此查詢返回任何結果:(SELECT * FROM表1 LEFT加入表2 0 = 1 LEFT加入表3 其中somedate <= table1.orderdate) UNION ALL (SELECT * FROM table1的RIGHT 0加入表2 = 1 LEFT加入表3 其中somedate <= table2.orderdate) UNION ALL (選擇從表1 RIGHT *加入0 = 1表2 RIGHT加入表3 其中somedate <= table3.orderdate)? – Egalitarian