0

我有一个表 [Transaction],用于存储用钱玩西洋双陆棋的玩家的交易价值。房子可以贷记(在游戏中购买并稍后付款)或借记(手头现金)。有四种类型的交易(借记、贷记)和(“贷记结算”——客户偿还部分或全部欠款,“借记结算”——如果房子欠玩家钱,则由房子支付)。我要做的是找到平衡。我已经尝试了很多 sql 语句,但我总是遗漏一些东西并且平衡不正确。

一个简单的场景是:客户走进来,以 300 的信用额度购买。他兑现了 100,所以他欠房子 200。第二天他来了,用 100 信用买进(所以现在他欠 300),最后兑现了 1000。房子付给他 500,但还欠他 200。房屋向客户支付 200,因此将其存储为“借方结算”。

在此处输入图像描述

这是我到目前为止的结果,但结果并不总是正确的:

SELECT     SUM(Cashout)  - ((SELECT     COALESCE (SUM(Paid), 0) AS Expr1
                            FROM          [Transaction]
                            WHERE      (Type = 'Credit Settlement'))  + SUM(Buyin) +
                          (SELECT     COALESCE (SUM(Paid), 0) AS Expr1
                            FROM          [Transaction] AS Transaction_3
                            WHERE      (Type = 'Debit Settlement') AND (Paid IS NOT NULL))) AS OutstandingDebit
FROM         [Transaction] AS Transaction_1
WHERE     (Type <> 'Debit Settlement') AND (Cashout >= 0) AND (CustomerID = 132)
4

1 回答 1

1

试试这个。我相信它有效。余额应为-200。我敢肯定,尽管有人可以对其进行编辑和优化,或者让它看起来更优雅!@贾斯汀,@蒂姆·罗杰斯,@nec tso

 SELECT (
 (SELECT coalesce(SUM(cashout),0)- 
                        ((select coalesce(sum(Buyin),0) from [Transaction] where TYPE='Credit' and CustomerID=132)
                         + (select coalesce(sum(Paid),0) from [Transaction] where TYPE='Credit' and CustomerID=132))


FROM [transaction]
WHERE TYPE='Credit'
AND CustomerID=132
)
-------------------
+
(
(SELECT coalesce(SUM(cashout),0)
                    - (select coalesce(sum(Paid),0) from [Transaction] where TYPE='Debit' AND Cashout>buyin and CustomerID=132) 
                    +  (select coalesce(sum(Cashout),0)- (select coalesce(sum(PAID),0) from [Transaction] where TYPE='Debit' AND Cashout<buyin and CustomerID=132)
                             from [Transaction] where TYPE='Debit' AND Cashout<Buyin and CustomerID=132)
                    +  (select coalesce(sum(Cashout),0)- (select coalesce(sum(PAID),0) from [Transaction] where TYPE='Debit' AND Cashout=buyin and CustomerID=132)
                             from [Transaction] where TYPE='Debit' AND Cashout=Buyin and CustomerID=132)
FROM [Transaction]
WHERE CustomerID=132
AND TYPE='Debit' 
AND Cashout>buyin )
)
--------------
-
(
select coalesce(sum(Paid),0)
from [Transaction] 
where type='Debit Settlement'
AND CustomerID =132
)
--------------
+
(
select coalesce(sum(Paid),0)
from [Transaction] 
where type='Credit Settlement'
AND CustomerID =132
)
);
于 2013-06-12T19:15:16.697 回答