(SQL)连接表并订购最终结果

时间:2012-05-20 04:33:54

标签: sql-server sql-order-by union left-join

table1table2table3包含不同的列,但所有列都有OrderDate列。我想从所有3个表中获取行的结果集,并且我希望最终结果集按OrderDate排序。

( 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返回错误&#34;如果语句包含UNION,INTERSECT或EXCEPT运算符,则ORDER BY项必须出现在选择列表中。&#34;

如果我更换

select *

通过

select *, table1.orderdate, table2.orderdate, table3.orderdate

我得到了同样的错误。

咦?感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我使用Common Table Expression解决了这个问题,这就是我所做的:

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.ID还是table2.ID还是table3.ID