【发布时间】:2019-12-27 01:01:46
【问题描述】:
我正在尝试编写一个 SQL 查询,返回每个州花费最多的五个客户的姓名和购买金额。
表架构
customers
|_state
|_customer_id
|_customer_name
transactions
|_customer_id
|_transact_amt
尝试看起来像这样
SELECT state, Sum(transact_amt) AS HighestSum
FROM (
SELECT name, transactions.transact_amt, SUM(transactions.transact_amt) AS HighestSum
FROM customers
INNER JOIN customers ON transactions.customer_id = customers.customer_id
GROUP BY state
) Q
GROUP BY transact_amt
ORDER BY HighestSum
我迷路了。谢谢。
预期结果是每个州交易量最高的前 5 名客户的姓名。
ERROR: table name "customers" specified more than once
SQL state: 42712
【问题讨论】:
-
如果出现并列第五名,您是想要全部(每个州可能超过 5 个),还是总是最多 5 个?
-
我只想返回每个州的前5名,谢谢
-
前10名花费相同的情况下,如何挑选“前5名”?请始终公开您的 Postgres 版本。
标签: sql database postgresql