答案 0 :(得分:1)
如果amount
对借记交易不利,会更容易。此外,余额为credit - debit
,而非debit - credit
。在任何情况下:
SELECT Userid, UserName, Dep_title,
( (SELECT COALESCE(SUM(amount), 0) FROM Transctions WHERE userid = USER.userid AND tr_type = 'Credit')
- (SELECT COALESCE(SUM(amount), 0) FROM Transctions WHERE userid = USER.userid AND tr_type = 'Debit')
) AS Balance
FROM USER
JOIN Department USING (dep_id)
答案 1 :(得分:1)
您可以尝试这样的事情:
SELECT
u.Userid AS Userid,
u.UserName AS UserName,
d.Dep_title AS Dep_title,
SUM(IF(t.tr_type='Credit',-1*t.amount,t.amount)) AS "Balance(Debit-Credit)"
FROM USER AS u
LEFT JOIN Departement AS d USING(dep_id)
LEFT JOIN Transactions AS t ON u.Userid=t.userid
GROUP BY u.Userid
答案 2 :(得分:0)
我认为您正在寻找的查询是......
SELECT Userid,
UserName,
(SELECT Dep_title
FROM department
WHERE USER.dep_id = department.dep_id) AS Dep_title,
((SELECT (SUM(amount)
FROM Transactions
WHERE Transactions.userid = USER.Userid AND
tr_type = 'Credit') -
(SELECT (SUM(amount)
FROM Transactions
WHERE Transactions.userid = USER.Userid AND
tr_type = 'Debit')) AS "Balance(Debit-Credit)"
FROM USER;
如果我可以接受一些观察;首先,您的最后一列标题似乎并不反映该列的内容,其次,您的表和列名称随意大写将在未来导致很多麻烦;我建议你使用一致的大写形式和缩写形成。
答案 3 :(得分:0)
这应该工作(不需要子选择,但是没有测试):
SELECT
USER.Userid,
USER.UserName,
Department.Dep_title,
SUM(IF(Transactions.tr_type='Credit',amount,amount*(-1))) as Balance
FROM
USER,
Department,
Transactions
WHERE
USER.Userid = Transactions.userid
AND
USER.dep_id = Department.dep_id
GROUP BY
USER.Userid
答案 4 :(得分:0)
Select U.UserId, U.Username, D.Dep_Title
, Coalesce(Sum( Case When T.tr_type = 'Debit' Then -1 Else 1 End * T.Amount )
,0) As [Balance (Debit-Credit)]
From Users As U
Join Department As D
On D.Dep_Id = U.Dep_Id
Left Join Transactions As T
On T.UserId = U.UserId
Group By U.UserId, U.Username, D.Dep_Title
答案 5 :(得分:0)
我没有对此进行过测试,但您应该能够使用IF
语句计算出信用卡和借记卡之间的差异。
SELECT u.Userid, u.UserName, d.Dep_title, t.Balance
FROM USER As u
LEFT JOIN Department AS d on u.dep_id = d.dep_id
LEFT JOIN (SELECT userid, SUM(IF(tr_type = 'Debit', amount, -1*amount)) AS Balance FROM Transactions GROUP BY userid) AS t