按 Id 和 Id 计数显示平均评分 Mysql

Display Average Rating by Id with Count of Ids Mysql

我有一个 MYSQL table,我想在其中获得带有产品 ID 计数的平均评分。这是 table.

的示例
╔════╦═════════════╦══════════╦══════════╗
║ ID ║ product_Id  ║ rating   ║ status   ║
╠════╬═════════════╬══════════╬══════════╣
║  1 ║ 5           ║ 1        ║        1 ║
║  2 ║ 5           ║ 3        ║        1 ║
║  3 ║ 5           ║ 4        ║        1 ║
║  4 ║ 4           ║ 3        ║        1 ║
║  5 ║ 4           ║ 5        ║        1 ║
║  6 ║ 6           ║ 4        ║        1 ║
║  7 ║ 6           ║ 4        ║        1 ║
╚════╩═════════════╩══════════╩══════════╝

我已经处理了这段代码,但没有得到想要的结果。

SELECT r.product_id, ROUND(AVG(r.rating),0) as avg_rating, COUNT(r.product_id) AS products_total FROM review r
                WHERE r.status = 1 
                GROUP BY r.product_id ASC

结果为平均评分(同一产品 ID 的评分数)

  1. 3(3)
  2. 4(2)
  3. 4(2)

我希望将结果打印为平均评分(具有相同评分的产品 ID 的数量)

  1. 3(1)
  2. 4(2)

我怎样才能达到上面的结果

如果我理解,那么你想要两个级别的聚合:

SELECT avg_rating, COUNT(*)
FROM (SELECT r.product_id, AVG(r.rating) as avg_rating, COUNT(r.product_id) AS products_total
      FROM review r
      WHERE r.status = 1 
      GROUP BY r.product_id
     ) p
GROUP BY avg_rating