4

我的表中有一个金额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

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

4

1 回答 1

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

于 2013-05-10T08:19:28.870 回答