我有一个表[交易],用于存储玩金枪鱼的玩家的交易价值。房子可以给予信用(在游戏中购买并稍后付款)或借记(手头支付现金)。有四种类型的交易(借方,贷方)和('信用结算' - 客户偿还他欠的部分或全部,以及'借方结算' - 如果房子向玩家欠钱,则由房屋支付)。我要做的是找到平衡点。我已经尝试了很多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)
答案 0 :(得分:1)
试试这个。我相信它有效。余额应为-200。 我敢肯定,虽然有人可以编辑它并优化它或使它看起来更优雅! @Justin,@ Tim Rogers,@ 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
)
);