在SQL中查找透支帐户

时间:2010-06-05 23:17:32

标签: sql

嘿伙计们,我有一个允许我对大型数据库运行查询的程序。 我现在有两张桌子很重要,存款和取款。每个都包含每个用户的历史记录。我需要拿每张桌子,将每笔存款加起来(每位用户),然后从存款中扣除。然后我需要返回每个结果为负的用户(也就是说他们退出了更多然后存入)。 这可能在一个查询中吗?
示例:

Deposit Table:
|ID|UserName|Amount| |1 | Use1 |100.00| |2 | Use1 |50.00 | |3 | Use2 |25.00 | |4 | Use1 | 5.00 |

WithDraw Table: |ID|UserName|Amount| |2 | Use2 | 5.00 | |1 | Use1 |100.00| |4 | Use1 | 5.00 | |3 | Use2 |25.00 |

So then the result would output: |OverWithdrawers| | Use2 |

这可能吗(我肯定不知道怎么做)? 谢谢你的帮助, 最大

3 个答案:

答案 0 :(得分:3)

试试这个:

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)

COALESCE如果有用户退出但从未存放过,也可以使用。

答案 1 :(得分:0)

另一种方法:

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

答案 2 :(得分:-1)

更正了工作版本:

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