sql - 对于 SQL,如何使用 group by 两次但仅在第二组内按 sum() 排序

标签 sql group-by sql-order-by

该表记录信用卡交易,其中每一行都是一条记录。

这些列是:transaction_id、customerID、dollar_spent、product_category。

如何从每个 Product_category 中选取该类别中 Dollar_spent 最高的 3 个 customerID?

我在想这样的事情:

select product_category, customerID, sum(dollar_spent) 
from transaction
group by product_category, customerID
order by sum(dollar_spent) desc limit 3

但未能通过。删除“限制 3”有助于它通过,但整个结果仅按 sum(dollar_spent) 排序,而不是按每个 Product_category 中的 sum(dollar_spent) 排序。

在 StackOverflow 上搜索但没有找到任何相关内容。有人可以帮我解决这个问题吗?非常感谢!!

最佳答案

我认为您正在寻找的是窗口函数。

我将 row_number 函数添加到您按花费金额排序的选择中,这基本上按产品对客户支出进行排名。

然后,由于您不能在 where 子句中使用窗口函数(不幸的是),我必须创建一个外部查询来过滤 row_number 结果

select * from( 
   select product_category, customerID, sum(dollar_spent), 
   row_number() over (partition by product_category order by sum(dollar_spent) desc) as rowNum
   from transaction
   group by product_category, customerID
) as data
where rowNum <= 3
order by product_category, rowNum

这是一个fiddle

关于sql - 对于 SQL,如何使用 group by 两次但仅在第二组内按 sum() 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69741980/

相关文章:

java - 由于底层异常 : java.net.ConnectException 导致通信链路失败:连接被拒绝:连接

mysql - 如何从一个查询中提取多个用​​户信息?

mysql - 使用 VBA 执行在文本框中编写的 SQL

Mysql select distinct only if certain time difference exist

c# - 使用来自 qrouped 数据的 linq 的条件平均不返回任何内容

sql - 返回一个表中的所有行,并与另一个表中的行的子集匹配?

sql - 如何在 SQL 中使用 union 进行排序?

c# - 尝试使用 IQueryable 自定义 OrderBy - "Skip"方法错误

linq - 按LINQ方法语法排序

sql-server - 使用 T-SQL 将 OHLC 股票市场数据分组为多个时间范围