使用SUM在列中查找总量,然后逐个分组

时间:2013-05-10 08:14:56

标签: mysql

我的transactions表中有一个金额列表。我想找出总金额大于person_id的每个50的总交易金额。

我希望这会有效,但事实并非如此:

SELECT (
    SELECT SUM(amount) 
    FROM transactions WHERE person_id = p.id
) AS total_amount
FROM people AS p 
WHERE total_amount > 50

我能让这个工作的唯一方法是:

SELECT (
    SELECT SUM(amount) 
    FROM transactions WHERE person_id = p.id
) AS total_amount
FROM people AS p 
WHERE (
    SELECT SUM(amount) 
    FROM transactions WHERE person_id = p.id
) > 50

..这是超级低效的。关于如何更好地格式化我的查询的任何建议?

1 个答案:

答案 0 :(得分:6)

尝试

SELECT person_id, SUM(amount)
  FROM transactions
GROUP BY person_id
HAVING SUM(amount) > 50

<强> SQLFiddle

更新: peopletransactions已加入

SELECT t.person_id, p.name, SUM(t.amount) amount
  FROM transactions t JOIN
       people p ON t.person_id = p.id 
GROUP BY t.person_id, p.name
HAVING SUM(t.amount) > 50

<强> SQLFiddle

相关问题