mysql - 使用 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
解决方案
您可以使用count(distinct ...)
:
select category, count(distinct product_id) cnt_distinct_products
from product
group by category
样本数据:
类别 | product_id :------- | ---------: 一个 | 1 一个 | 1 一个 | 2 乙 | 3 乙 | 3 乙 | 5
结果:
类别 | cnt_distinct_products :------- | --------------------: 一个 | 2 乙 | 2
推荐阅读
- wordpress - 停用产品的悬停效果,让“数量”和“购买”按钮始终可见
- javascript - 难以将值存储在 const 中并保持输入值的状态(不是道具)
- dart - 是否可以使用 .where() 来“断言”一个类型?
- node.js - 如何以json字符串作为值解析json
- python - 使用 Python 进行 FFT
- visual-studio - 如何在 Visual Studio 中选择下一个重复选择?
- minizinc - Minizinc 目标函数用于计划中的差距
- cadence-workflow - 工作流事件的重新排序
- birt - 无法使用 javascript 设置 Birt 图表的 SeriesIdentifier
- node.js - 不生成招摇文档 - Node JS + swaggerJSDoc