简体   繁体   中英

Count same AND different values

At the restaurant, a group of friends (each with their own user_id ) ate two or more things (each with their own item_id ).

In the database is saved who ( user_id ) ate what ( item_id ).

How can I find ONLY who ( user_id ) has eaten DIFFERENT things ( item_id )? In other words, I want to exclude from the results those who ate the same thing twice.

The following query shows me who has eaten more than one thing, without however excluding those who have eaten the same thing twice (which I don't care):

SELECT
    `user_id`, DATE(date), `item_id`, COUNT(*)
FROM `restaurant`
GROUP BY
    `user_id`, DATE(date)
HAVING 
    COUNT(*) > 1

Thanks

COUNT(*) counts every row for each group of user_id and DATE(date) .

If you want it to count only different item_id s you need the keyword DISTINCT :

SELECT user_id, DATE(date), 
       COUNT(DISTINCT item_id)
FROM restaurant
GROUP BY user_id, DATE(date)
HAVING COUNT(DISTINCT item_id) > 1;

Note that item_id does not make sense in the SELECT list.

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