简体   繁体   中英

Can you group and count in mysql on different columns?

Users have a list with items in different categories. I want to know how many items a user has in each category.

User    |   item  | category
____________________________
Bill    |   car   | new
Bill    |   truck | used
Bill    |   boat  | new
Bill    |   house | old
Sue     |   car   | used
Sue     |   truck | used
Bill    |   bike  | new
Sue     |   viola | used

I'd like the results

User category
__________________________
Bill|  new   |  3
Bill|  used  |  1
Bill|  sold  |  1

I've tried

$SQL = "SELECT COUNT(DISTINCT CATEGORY) FROM LIST WHERE USER=Bill";

but it doesn't get me very far.

Thanks

You need to use group by statement:

select user, category, count(distinct item)
from mytable
where user = 'Bill'
group by user, category

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