0

table1,table2并且table3有不同的列,但都有一个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 返回错误“如果语句包含 UNION、INTERSECT 或 EXCEPT 运算符,则 ORDER BY 项必须出现在选择列表中。”

如果我更换

select *

经过

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

我犯了同样的错误。

嗯?谢谢。

4

2 回答 2

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
于 2012-05-20T05:03:33.310 回答
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...]

如果, ,具有相同的列名(例如),*则无法避免替换,否则 SQL Server 会抛出一个错误,说是模棱两可的:它无法知道这是否意味着or或。table1table2table3IDJoinedTable.IDtable1.IDtable2.IDtable3.ID

于 2012-05-20T20:16:37.397 回答