2012-05-20 32 views
0

table1table2table3有不同的列,但都有一個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 

我得到同樣的錯誤。

咦?謝謝。

回答

0

我解決了使用公共表表達式的問題,這裏是我做過什麼:

WITH JoinedTable as 
(
    (select table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 
     from table1 LEFT join table2 on 0=1 LEFT join table3 on 0=1 
     where somedate <= table1.orderdate) 

    union all 

    (select table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 
     from table1 RIGHT join table2 on 0=1 LEFT join table3 on 0=1 
     where somedate <= table2.orderdate) 

    union all 

    (select table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 
     from table1 RIGHT join table2 on 0=1 RIGHT join table3 on 0=1 
     where somedate <= table3.orderdate) 
) 

select *, case when t1orderdate is not null then t1orderdate 
       when t2orderdate is not null then t2orderdate 
       else t3orderdate end 
       AS DateForOrderingResultSet 
from JoinedTable order by DateForOrderingResultSet 

table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 

它取代無法避免*如果table1table2,table3具有相同的列名稱(例如ID),否則SQL Server會引發錯誤,說明JoinedTable.ID含糊不清:它無法知道這是否意味着table1.IDtable2.IDtable3.ID

1

嘗試這個

Select * from 
((select * from table1 LEFT join table2 on 0=1 LEFT join table3 
    where somedate <= table1.orderdate) 

union all 

(select * from table1 RIGHT join table2 on 0=1 LEFT join table3  
    where somedate <= table2.orderdate) 

union all 

(select * from table1 RIGHT join table2 on 0=1 RIGHT join table3 
    where somedate <= table3.orderdate)) A 

Order by A.orderdate 
+0

SQL Server引發錯誤,指出'A'列多次指定'ID'列。但即使這是用別名解決的,你是否想使用table1,table2或table3的orderdate?這就是問題所在,在結果集的任意一行中,3列中的2列table1.orderdate,table2.orderdate,table3.orderdate爲null,因爲這是外連接。我想根據非空值的結果集對結果集進行排序... – SemMike

+0

您可以使用where子句並指定:其中A.orderDate不爲空。順便說一句 – Egalitarian

+0

執行此查詢返回任何結果:(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