简体   繁体   中英

MySQL: Return the Count of a distinct rows of a group

I'm having trouble with combining the count/grouping feature with the distinct feature. In my database I have a table (BurgerOrders) with the an orderID and burgerId (which is the type of burger).

An order can contain multiple burgers, it could contain 3 burgers of the same burgerId or 3 different burgers. I'm trying to find out how to get the count of DISTINCT burgers. I'm able to get the count of total burgers in any order, but can't figure out how to make it's the count of distinct burgers only.

Below is the query I've tried which doesn't work in due to invalid syntax but hopefully gives an idea of what I'm trying to do.

SELECT orderId, COUNT(*)
FROM BurgerOrders
GROUP BY orderId
HAVING DISTINCT burgerId;

I know it's the last line that causes the error. I'm not sure whether it's possible to use a single query or a subquery is necessary.

Thanks in advance for any help!

I think what you are looking for is something like this:

SELECT orderId, COUNT(DISTINCT burgerId) 
FROM BurgerOrders 
GROUP BY orderId;

The HAVING syntax requires a condition, see for example here: https://www.w3schools.com/sql/sql_having.asp

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