简体   繁体   中英

sum certain columns of 2 tables matching criteria sql

Table1 data:

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

Table2 data:

ACType P1hr Total

A320    5     5

on comparing the 2 tables,what sql query will give me result:

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

which should also factor case when Table1 is empty,so to give result:

ACType Dualhr P1hr Total 
A320     0      5    5

Use union and subquery:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM