[英]Group union query by column in 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
這可能嗎?
然后,您似乎想要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。 這是大多數數據庫認可的標准格式。
您不需要使用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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.