首页 > 解决方案 > 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        |
+--------------+---------+---------+

标签: mysql

解决方案


您可以使用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

推荐阅读