3

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.

1
  • 1
    Trick Question :) Commented Jul 5, 2013 at 5:09

4 Answers 4

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

SQL FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

4

Try HAVING with self-join:

SELECT T1.[User] FROM MyTable T1
  JOIN MyTable T2
    ON T1.[User] = T2.[User]
   AND T2.[Type] = 'Soccer'
GROUP BY T1.[User]
HAVING COUNT(T1.[Type]) = 1;

See this SQLFiddle

3 Comments

you will need to add a where clause with WHERE type = 'Soccer'
@hims056 Please see your answer Logically you are wrong.
Thank hims056! It worked. I appreciate the help. Still trying to weed myself through sql
1

Try this

SELECT [User] FROM Table1 T1
WHERE EXISTS (SELECT T2.[User] FROM Table1 T2 WHERE T2.[User] = T1.[User]
             AND T2.[Type] = 'Soccer')
GROUP BY [User]
HAVING COUNT([User]) = 1

1 Comment

Please see your answer Logically you are wrong.
1

Query:

SQLFIDDLEExample

SELECT t1.[User] 
FROM [MyTable] t1
WHERE t1.Type = 'Soccer'
AND NOT EXISTS (SELECT 1
                FROM MyTable t2
                WHERE t2.[User] = t1.[User] 
                AND t2.Type != t1.Type)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.