我有两个表:
1个付款表
PID Amount IsOk
=======================
10 50 true
10 92 false
14 73 true
14 22 true
15 10 true
2提现表
PID Amount IsOk
=======================
10 23 true
14 98 false
14 15 true
我想要subtract(sum of withdraws amounts) and (sum of withdraws amounts) where IsOk=true
这样的任何PID
PID Balance
=======================
10 27 //50-23
14 80 //73+22-15
15 10 //10
一个选项使用union all
和聚合:
select pid, sum(amount) balance balance
from (
select pid, amount from payment where isOk = 'true'
union all
seect pid, -amount from withdraws where isOk = 'true'
) t
group by pid
我认为您正在寻找
SELECT T.PID, SUM(T.Amount) - SUM(DISTINCT ISNULL(TT.Amount, 0))
FROM
(
VALUES
(10, 50, 1),
(10, 92, 0),
(14, 73, 1),
(14, 22, 1),
(15, 10, 1)
) T(PID, Amount, IsOk)
LEFT JOIN
(
VALUES
(10, 23, 1),
(14, 98, 0),
(14, 15, 1)
) TT(PID, Amount, IsOk)
ON T.PID = TT.PID AND TT.IsOk = 1
WHERE T.IsOk = 1
GROUP BY T.PID;
哪个会返回:
+-----+------------------+
| PID | (No column name) |
+-----+------------------+
| 10 | 27 |
| 14 | 80 |
| 15 | 10 |
+-----+------------------+
这里是db<>fiddle