簡體   English   中英

從兩個表中計算用戶賬戶余額

[英]Calculate the user account balance from two tables

我有兩張桌子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM