Reputation: 1582
I have a table with a UserID and ImageID Column. I want to select all the UserId's with only one ImageID. I have the code below.
Select UserID From AF.UserImageTable
Where Count(ImageId) = 1
When I run the code I get the error.
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
The table looks like this
_________________________
: ImageID : UserID :
: 12345 : 10002 :
: 56789 : 10002 :
: 29292 : 10002 :
: 12345 : 10001 :
: 56789 : 10001 :
: 56789 : 10003 :
________________________
If I run the Query on the table above I'm trying to get it to return 10003
Upvotes: 3
Views: 2413
Reputation: 85
I see you have several ImageID's shared by multiple UserID's, is this only for example or do you also need to exclude these cases? If you want to get out of grouping limitations, you could also try a sub query. You can get all data from your table, and can easily change if you want to view people with one image only, or two images only, etc...
SELECT AF.ImageID, AF.UserID
FROM UserImageTable AF
WHERE AF.UserID IN (
SELECT AF2.UserID
FROM UserImageTable AF2
GROUP BY UserID
HAVING COUNT(AF2.ImageId) = 1--Switch to 2 or 3 for more images.
)
Upvotes: 0
Reputation: 176
If you also need to get [ImageID] values there is query:
SELECT UserID, max(ImageID) as ImageID
FROM AF.UserImageTable
GROUP BY UserID
HAVING COUNT(ImageId) = 1
Upvotes: 1
Reputation: 4375
When you use the below group by clause with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows(in this case UserID and aggregates their values) and then the HAVING clause eliminates groups that you dont need.
Select UserID,count(ImageId) From AF.UserImageTable
group by UserID having Count(ImageId) = 1
Upvotes: 4
Reputation: 3108
try :
Select UserID
From AF.UserImageTable
Group By UserID
Having Count(ImageId) = 1
Upvotes: 1