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返回错误&#34;如果语句包含UNION,INTERSECT或EXCEPT运算符,则ORDER BY项必须出现在选择列表中。&#34;
如果我更换
select *
通过
select *, table1.orderdate, table2.orderdate, table3.orderdate
我得到了同样的错误。
咦?感谢。
答案 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...]
如果*
,table1
,table2
具有相同的列名(例如table3
),则无法避免取代ID
的,否则SQL Server会抛出错误说JoinedTable.ID
含糊不清:无法知道这是table1.ID
还是table2.ID
还是table3.ID
。