2012-05-20 30 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