简体   繁体   English

MySQL - 按标准分组AND计数组合在一起的项目数 - 如何?

[英]MySQL - group by criterion AND count # of items that are grouped together - how?

Is there a way to execute 1 query that would select all items ("SELECT * FROM t-shirts ), group them by certain criterion ("GROUP BY style , color ") but at the same time count the # of UNIQUE 'color' items that were grouped together? I can do that by cycling through each style->color and count the number of items, but I thought that perhaps there's an easier way of doing that. 有没有办法执行1个查询,选择所有项目(“SELECT * FROM t-shirts ),按特定标准(“GROUP BY stylecolor ”)对它们进行分组,但同时计算UNIQUE'颜色'#组合在一起的项目?我可以通过循环每个样式 - >颜色并计算项目数量来做到这一点,但我想也许有一种更简单的方法。

Thanks. 谢谢。

PS Solved: remove color from GROUP BY, and used "COUNT (distinct color)": PS Solved:从GROUP BY中删除color ,并使用“COUNT(不同颜色)”:

SELECT *, COUNT (distinct color) FROM t-shirts GROUP BY style
SELECT COUNT(`field`), `style` FROM `t-shirts` GROUP BY `style`

field是主键。

尝试SELECT style, COUNT(*) FROM t-shirts GROUP BY style

SELECT style, COUNT(*) AS cnt 
FROM `t-shirts` 
GROUP BY style

Count是一个组函数,也可以与select *一起使用:

SELECT *, COUNT(`field`) FROM `t-shirts` GROUP BY `style`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM