mysql - MySQL查询以按另一列获取平均项目数
问题描述
我有这个 MySQL 表:
+--------------+---------+---------+
| email | itemSku | orderId |
+--------------+---------+---------+
| 1@test.com | abc | 1 |
| 1@test.com | def | 1 |
| 1@test.com | ghi | 1 |
| 1@test.com | jkl | 1 |
| 1@test.com | mno | 1 |
| 1@test.com | pqr | 1 |
| 1@test.com | abc | 2 |
| 1@test.com | def | 2 |
| 2@test.com | abc | 3 |
| 2@test.com | def | 3 |
| 2@test.com | ghi | 3 |
| 2@test.com | abc | 4 |
| 2@test.com | def | 4 |
+--------------+---------+---------+
我想知道每封电子邮件的每个 orderId 的不同 itemSku 的平均数量。
结果将是:
+--------------+-------------------+
| email | avgNbItemPerOrder |
+--------------+-------------------+
| 1@test.com | 4 |
| 2@test.com | 2.5 |
+--------------+---------+---------+
解决方案
您可以使用GROUP BY
两次,如:
select
email, avg(c)
from (
select email, orderid, count(distinct itemsku) as c
from t
group by email, orderid
) x
group by email
推荐阅读
- azure - Devops Azure 没有足够的钩子权限(协作者)
- php - 将数据从 JSON 插入 MySQL 数据库表
- c# - 如何在 Microsoft Visual Studio 安装程序中选择性地创建快捷方式
- r - 尝试从 json 文件中提取列表时如何解决“$ 运算符对原子向量无效”?
- intellij-idea - Kotlin/JVM 编译器对条件函数引用进行故障排除
- unity3d - 3D AR 物体在 Vuforia 中晃动
- python - 如何使用容器化 VPN 并从 docker python 应用程序写入主机 PostgreSQL 数据库
- python - 在具有不同要求的矩形上创建缓冲区
- powershell - 比较日期并分配给每个变量
- c# - % 不能分配给十进制类型 C#