首页 > 解决方案 > 使用 mysql 查询基于不同组获取 product_id 列的不同计数

问题描述

我想通过在类别列上应用 group by 子句来获得基于类别列的 product_id 列的总数,我为此编写了 mysql 查询,但它没有按照我的要求工作。

mysql查询:

SELECT DISTINCT category  FROM `product`  group by product_id,category

桌子:

category      product_id
a              1        
a              1
a              2
b              3   
b              3
b              5

预期输出:

 category    count(product_id)
 a            2
 b            2

标签: mysqlsqlgroup-bycount

解决方案


您可以使用count(distinct ...)

select category, count(distinct product_id) cnt_distinct_products 
from product 
group by category

DB Fiddle 上的演示

样本数据:

类别 | product_id
:------- | ---------:
一个 | 1
一个 | 1
一个 | 2
乙 | 3
乙 | 3
乙 | 5

结果:

类别 | cnt_distinct_products
:------- | --------------------:
一个 | 2
乙 | 2

推荐阅读