我的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
..这是超级低效的。关于如何更好地格式化我的查询的任何建议?
答案 0 :(得分:6)
尝试
SELECT person_id, SUM(amount)
FROM transactions
GROUP BY person_id
HAVING SUM(amount) > 50
<强> SQLFiddle 强>
更新: people
和transactions
已加入
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 强>