[英]how to substract between two tables by comparing them( according to a condition ) in sql?
我有两张这样的桌子
表格1
------------------------------------
date | name | charge | coupon|
------------------------------------
10/01 | Alex | 500 | 100 |
11/01 | Max | 1000 | 200 |
13/01 | | | |
表2
------------------------------------
date | name | error | refund |
------------------------------------
10/01 | Alex | crash | |
| | | |
如果table2中有错误,我想计算从table1到table2的退款。 考虑日期和名称是唯一的。
我尝试过这样的事情,但它根本不正确。 我是 SQL 的初学者
SELECT date, name, charge - coupon as Refund IF( error=True FROM table2 )
FROM table1
请帮助如何解决这个问题...
嗯。 . . 我想你想join
:
select t2.*, (t1.charge - t1.coupon) as refund
from table2 t2 join
table1 t1
on t1.name = t2.name and t1.date = t2.date
where t2.error is not null;
如果您想要所有行,并有条件地退款:
select t2.*,
(case when t2.error is not null then t1.charge - t1.coupon end) as refund
from table2 t2 join
table1 t1
on t1.name = t2.name and t1.date = t2.date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.