table1
table2
和table3
有不同的列,但都有一个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
我得到同样的错误。
咦?谢谢。
SQL Server引发错误,指出'A'列多次指定'ID'列。但即使这是用别名解决的,你是否想使用table1,table2或table3的orderdate?这就是问题所在,在结果集的任意一行中,3列中的2列table1.orderdate,table2.orderdate,table3.orderdate为null,因为这是外连接。我想根据非空值的结果集对结果集进行排序... – SemMike
您可以使用where子句并指定:其中A.orderDate不为空。顺便说一句 – Egalitarian
执行此查询返回任何结果:(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