SQL 组人数相等的订单

SQL order with equal group size

我有一个包含 monthnametransaction_id 列的 table。我想统计每个月的交易次数和姓名。但是,对于每个月,我都希望获得交易量最高的前 N 个名称。

以下查询按 monthname 分组。但是 LIMIT 应用于完整结果而不是每个 month:

SELECT
    month,
    name,
    COUNT(*) AS transaction_count
FROM my_table
GROUP BY month, name
ORDER BY month, transaction_count DESC
LIMIT N

有谁知道我如何才能获得每个 month 的前 N 个结果?

使用row_number():

SELECT month, name, transaction_count
FROM (SELECT month, name, COUNT(*) AS transaction_count,
             ROW_NUMBER() OVER (PARTITION BY month ORDER BY COUNT(*) DESC) as seqnum
      FROM my_table
      GROUP BY month, name
     ) mn
WHERE seqnum <= N
ORDER BY month, transaction_count DESC