首页 > 解决方案 > MySQL 按聚合函数分组

问题描述

对不起,如果我听起来完全是新手,但我知道我离解决这个问题还有一步之遥。有什么办法可以分组number_of_trans吗?我想知道有多少用户有相同的交易数量,按交易数量分组。我的查询是这样的:

SELECT
  cust_id, COUNT(*) AS number_of_trans
FROM
  table
GROUP BY
  cust_id
HAVING COUNT(*) > 1
ORDER BY
  number_of_trans

我得到的结果是这样的

+------------------+--------------+
| cust_id          | numb_of_trans|
+------------------+--------------+
| 01               |  2           |
| 02               |  3           |
| 03               |  3           |
| 04               |  4           |
| 05               |  4           |
+------------------+--------------+

虽然我期待这样的结果:

+------------------+--------------+
| numb_of_trans    | count        |
+------------------+--------------+
| 1                |  null        |
| 2                |  1           |
| 3                |  2           |
| 4                |  2           |
| 5                |  null        |
+------------------+--------------+

标签: mysqlsqlgroup-bycount

解决方案


您可以left join使用数字列表对当前的聚合查询进行聚合,然后再次聚合:

select 
    n.number_of_trans,
    count(*) cnt
from (
    select 1 number_of_trans
    union all select 2
    union all select 3
    union all select 4
    union all select 5
) n
left join (
    select count(*) as number_of_trans
    from mytable
    group by cust_id
    -- having count(*) > 1
) t on t.number_of_trans = n.number_of_trans
group by n.number_of_trans
order by n.number_of_trans

union all如果需要,您可以使用更多数字扩展子查询。

我不确定您是否确实需要having在聚合查询中过滤掉cust_id只有一个条目的 s 的子句,因此我对其进行了评论 - 根据需要随时取消评论。

另请注意,这将产生0而不是聚合子null查询number_of_trans中不存在的。如果你真的想要null,那么你可以这样做:

nullif(count(*), 0) cnt

推荐阅读