Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL matching multiple values to various values in same table

Tags:

sql

sql-server

I am having some issues in trying to get my query to work. I am not that efficient with SQL Server.

I have a table that has an user id column and the user id matches different values in the type column so the data looks like this

User | Type 
User1 | Soccer 
User1 | Tennis 
User1 | BasketBall 
User2 | Tennis 
User2 | Swimming 
User3 | Soccer 
User3 | Swimming 

I want to be able to get all users that that belong to only one type (Soccer) but do not belong to any other types. So they should only have one type they belong to in the database.

like image 418
Danny Avatar asked May 21 '26 23:05

Danny


1 Answers

SELECT [User] FROM Table1
GROUP BY [User]
HAVING COUNT([Type]) = 1
and max([Type])='Soccer'
and min([Type])='Soccer'

SQL FIDDLE

like image 112
Prahalad Gaggar Avatar answered May 23 '26 13:05

Prahalad Gaggar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!