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

时间:2018-08-14 07:09:28

标签: mysql

表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

当Table1为空时,这也应该考虑大小写,以便得出结果:

ACType Dualhr P1hr Total 
A320     0      5    5

1 个答案:

答案 0 :(得分:0)

使用联合和子查询:

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