mysql - 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 |
+------------------+--------------+
解决方案
您可以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
推荐阅读
- typescript - typecirpt 不理解我的验证功能logicallay
- c++ - 在非默认构造函数中使用默认构造函数
- python - 为python多处理创建非常大的队列
- dependency-injection - 洋葱架构中的依赖规则令人困惑
- python-3.x - 为什么输出不同?(如何使 print(s1) 输出日语)
- javascript - LocalStorage 变量未在 Chromium Kiosk 模式下持续存在
- iis - 无法启动 asp.net core 2.1 webapi
- php - 在 PHP 和 MYSQL 的输入中从数据库中的哈希密码中获取原始密码
- c++ - 存储涉及引用的“方程式”的库?
- angular - 如何在 Nativescript 中使用原生 Android 类