SQL将多个值与同一个表中的各种值匹配

时间:2013-07-05 04:54:38

标签: sql sql-server

我在尝试让我的查询工作时遇到了一些问题。我对SQL Server效率不高。

我有一个具有用户ID列的表,并且用户ID匹配type列中的不同值,因此数据看起来像这样

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

我希望能够获得仅属于一种类型(Soccer)但不属于任何其他类型的所有用户。所以他们应该只有一个他们属于数据库的类型。

4 个答案:

答案 0 :(得分:4)

尝试使用自我加入HAVING

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;

请参阅this SQLFiddle

答案 1 :(得分:4)

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

<强> SQL FIDDLE

答案 2 :(得分:1)

试试这个

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

答案 3 :(得分:1)

查询:

<强> 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)