i have 3 tables see the picture
i want the sql statement which produde report like Required Report in pic.
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
I think the query you are looking for is...
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;
If I might be permitted a couple of observations; first, your last column title does not appear to reflect the contents of the column, and second, the haphazard capitalisation of your table and column names will lead to a great deal of trouble in the future; I recommend you use a consistent style for capitalisation and abbreviation forming.
It would be easier if amount
was negative for debit transactions. Also, the balance is credit - debit
, not debit - credit
. In any case:
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)
this should work (no need for subselects, but this isn't tested):
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
You could try something like this:
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
I haven't tested this but you should be able to use the IF
statement to work out the difference between credit and debit.
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