在SQL中按列分组并集查询

时间:2018-10-01 20:21:58

标签: sql

我要用一个联合查询2个表:

select date, A, B 
from table1 
where SERIAL_NUMBER = 1234
  and date > 'Sep 10 2018' 
  and date < 'Sep 20 2018' 

union 

select date, C, D 
from table2
where SERIAL_NUMBER = 1234
  and date > 'Sep 10 2018' 
  and date < 'Sep 20 2018' 
order by date

结果如下:

date1 a1 b1
date1 c1 d1
date2 a2 b2
date2 c2 d2

但是我想要类似的东西:

date1 a1 b1 c1 d1
date2 a2 b2 c2 d2

这可能吗?

2 个答案:

答案 0 :(得分:1)

然后您似乎想要join

select t1.date, t1.a, t1.b, t2.c, t2.d
from table1 t1 join
     table2 t2
     on t1.date = t2.date and t1.serial_number = t2.serial_number
where t1.SERIAL_NUMBER = 1234 and t1.date > '2018-09-10' and t1.date < '2019-09-20'
order by t1.date;

取决于您要如何处理丢失的日期,您可能希望使用full join而不是inner join

还要注意,我将日期格式更改为YYYY-MM-DD。这是大多数数据库认可的标准格式。

答案 1 :(得分:0)

您无需使用UNION ALL,而不必使用JOIN

select t1.date, t1.A, t1.B ,t2.C, t2.D 
from table1 t1 JOIN table2 t2 on t1.date = t2.date
where t1.SERIAL_NUMBER = 1234
and t1.date > 'Sep 10 2018' 
and t1.date < 'Sep 20 2018'