tags:

views:

83

answers:

3
A: 

Corrected working version:

Select innersql.UserName from (
    select 
          d.username,
          SUM(d.Amount) as depositamount,
          SUM(w.WithDraw)as withdrawamount 
    from deposit d
    inner join withdraw w
    on d.UserName = w.UserName
    group by d.UserName
     ) as innersql where depositamount > withdrawamount
Patrick Säuerl
above answear from matt is better because of using having
Patrick Säuerl
This also returns the wrong answer. It returns use1 instead of use2.
Mark Byers
Sorry, i used less than instead of greater than, corrected itI also got a question:As i see, the primary key in the tables is the ID and shouldn´t it be ID and Username ?
Patrick Säuerl
+3  A: 

Try this:

SELECT T1.UserName
FROM
(
    SELECT UserName, SUM(Amount) AS Amount
    FROM WithDraw
    GROUP BY UserName
) T1
LEFT JOIN
(
    SELECT UserName, SUM(Amount) AS Amount
    FROM Deposit
    GROUP BY UserName
) T2
ON T1.UserName = T2.UserName
WHERE T1.Amount > COALESCE(T2.Amount, 0)

The COALESCE is so that it also works if there are users that have withdrawn but never deposited.

Mark Byers
+1: Mine was equivalent, but had a redundant JOIN
OMG Ponies
Thanks! Works like a charm.
mazzzzz
A: 

An alternative method:

SELECT UserName, SUM(Amount) AS Amount
FROM (
    SELECT UserName, Amount
    FROM Deposit
    UNION ALL
    SELECT UserName, -Amount
    FROM WithDraw
) AS U (UserName, Amount)
GROUP BY UserName
HAVING SUM(Amount) < 0
Cade Roux