I have three tables:
Users
UserId
CategoryId
Categories
CategoryId
CategoryName
Addresses
AddressId
UserId
AddressValue
Users have to be in a category, but they don’t have to have an address. They can have more than one address.
I want to return the number of users in each category who have at least 1 address. So, I need to return something like CategoryId,NumberOfUsers,NumberOfUsersWithAddresses, where the following condition holds:
NumberOfUsers >= NumberOfUsersWithAddresses
I have this to return the number of users in each category:
SELECT
Categories.CategoryId, COUNT(Users.NumberOfUsers) AS Occurances
FROM
Users INNER JOIN
Categories on Users.CategoryId = Categories.CategoryId
GROUP BY
Categories.CategoryId
I tried this:
SELECT
Categories.CategoryId, COUNT(Users.NumberOfUsers) AS Occurances
(SELECT Count(Users.UserId)
FROM Addresses INNER JOIN Users on Addresses.UserId = Users.UserId
WHERE Users.CategoryId = Category.CategoryID
GROUP BY Users.CategoryID) AS NumberOfUsersWithAddresses
FROM
Users INNER JOIN
Categories on Users.CategoryId = Categories.CategoryId
GROUP BY
Categories.CategoryId
But this didn’t work – it returns the number of addresses in each category, rather than the number of users with addresses in each category. So if a user has two addresses, she counts as a ‘2’ rather than a ‘1’ in the sum.
What query do I need to make this work?
Not too fancy but a subquery in the
SELECTclause might do it.AFAIK, the
COUNT(DISTINCT u.UserID)was all you missed.or