对符合条件sql的2个表的某些列求和

mnemlml8  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(308)

表1数据:

ACType Dualhr P1hr Total 
A320     2     2    4
B787     1     2    3
B777     3     1    4

表2数据:

ACType P1hr Total

A320    5     5

比较这两个表时,sql查询将给出以下结果:

ACType Dualhr P1hr Total 
A320     2     7     9
B787     1     2     3
B777     3     1     4

当表1为空时,也应考虑情况,以便给出结果:

ACType Dualhr P1hr Total 
A320     0      5    5
1szpjjfi

1szpjjfi1#

使用并集和子查询:

select ACType, sum(Dualhr) as Dualhr, sum(P1hr) as P1hr,sum(Total) as Total 
from
(
select ACType, Dualhr, P1hr, Total from table1
union all
select ACType, 0, P1hr, Total from table2)a
group by ACType

相关问题