I have a table with a userID field and an itemID field. I would like to select all of those users that have two or more instances where itemID is the same (that is, if for example there are 3 records where userID = 1 and itemID = 7 then I would like those results, but not if there's just one instance). I need to get all users (not just results for a certain userID). Can anybody suggest how I could do this? Thanks.
You can do this using aggregation and a having
clause. If you just want the users:
select distinct userID
from t
group by userId, itemID
having count(*) >= 2;
This is an interesting query because it is one of the very rare situations where group by
and select distinct
are used together. If you wanted the userId
/ itemId
pairs, then you would use select userId, itemId
, without the distinct
.
You just need to use group by and having. The having clause is like where except that it also works on aggregations. So it's something like select userID, itemID, count(*) from mytable group by userID, itemID having count(*) > 1
.
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.