简体   繁体   中英

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.

Thanks.

PS Solved: remove color from GROUP BY, and used "COUNT (distinct color)":

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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