SQL减去2 select语句的结果

时间:2018-04-24 13:31:00

标签: mysql sql

我有两个查询完全可以完全隔离:

SELECT patient.patient_id, sum(cost)
FROM patient, appointment 
WHERE patient.patient_id = appointment.patient_id 
GROUP BY patient.patient_id
SELECT sum(payment_amount)
FROM patient, payment
WHERE patient.patient_id = payment.patient_id
GROUP BY patient.patient_id

我想知道的是如何从第一个查询中减去第二个查询的结果,以便在patient表中创建current_balance字段?

2 个答案:

答案 0 :(得分:2)

将两个quires汇总为一个,然后扣除SUM s。

SELECT pat.patient_id, SUM(cost) SUMCOST, SUM(payment_amount) SUMpayment_amount, SUM(cost) - SUM(payment_amount) current_balance 
FROM patient pat
INNER JOIN payment pay ON pat.patient_id = pay.patient_id 
INNER JOIN appointment app ON pat.patient_id = app.patient_id
GROUP BY pat.patient_id

答案 1 :(得分:0)

我强烈推荐这样的方法:

select patient_id, sum(cost) as cost, sum(payment) as payment,
       sum(cost) - sum(payment) as balance
from ((select a.patient_id, cost as cost, 0 as payment
       from appointment a
      ) union all
      (select p.patient_id, 0 as cost, payment
       from payment p
      )
     ) ap
group by patient_id;