从2表中获取数据并对结果的值求和

时间:2017-06-14 14:39:35

标签: mysql sql

我有2个包含信息的表: ID,persona_id,total_amount 角色ID可以重复十几次。所以我通过查询得到所有一个人的身份total_amount:

select d.id as debt_id, p.name as persona, sum(d.total_amount) as total_amount 
from debt d 
     join persons p on d.persona_id = p.id group by p.name

我希望在一个查询中从每个表中获取数据,并使用total_amount列执行aritmethic propertys并将其返回为1个表格。

表1

id persons_id total_amount
1   2         50
2   3         100
3   2         200
4   5         300
5   1         500

表2

id persons_id total_amount
1   2         25
2   1         100
3   5         50
4   3         100
5   4         300

因此,我希望得到2个表与总量列的算术运算( - ,+,/,*)相结合。基本上是一个更改,以获得表单中我想要的不同情况的结束总量。 / p>

基于JohnHC answear对我有用的是:

select c.id, c.persona_id, c.total_amount - d.total_amount as new_total

from (          select c.id , c.persona_id, sum(c.total_amount) as total_amount from credit c
                join persons p on c.persona_id = p.id
                group by p.name) c
inner join (    select d.id, d.persona_id, sum(d.total_amount) as total_amount from debt d
                join persons p on d.persona_id = p.id 
                group by p.name) d

on c.persona_id = d.persona_id
group by c.id, c.persona_id

1 个答案:

答案 0 :(得分:1)

如果你想要总数,请尝试:

select id, person_id, sum(total_amount)
from
(
select id, person_id, total_amount
from table1
union all
select id, person_id, total_amount
from table2
)
group by id, person_id

如果您想做其他事情,请尝试:

select t1.id, t1.person_id, t1.total_amount [+ - / *] t2.total_amount as new_total
from table1 t1
inner join table2 t2
on t1.id = t2.person_id
group by t1.id, t1.person_id