我想在两个不同的表上汇总信息

时间:2017-11-15 17:40:20

标签: mysql sql sqlite

我有两个表格如下,我希望得到像

这样的结果

第一个表格 - >

name    properties  piece
A            X       50
B            Y       40
A            Z       20
B            Y       10
A            X       15

第二个表格 - >

name    properties  piece
A            X       10
B            Y       10
A            Z       10
B            Y       15

我想要的结果

name    properties  piece
A            X       55
A            Z       10
B            Y       40

A-X的计算值(50 + 15-10 = 5)

1 个答案:

答案 0 :(得分:2)

select name, properties, sum(piece) from (
  select name, properties, piece from first_table 
  union all 
  select name, properties, -1 * piece from second_table
) a 
group by name, properties

这样做