查询以查找代表多个国家/地区的玩家

时间:2016-11-02 11:58:08

标签: sql sql-server

表: Sample table image

PlayerID | PlayerName |Country
---------+------------+---------
1001     | Virat      | Ind
1001     | Virat      | USA
1002     | Dave       | Aus
1003     | Paul       | Ireland
1005     | Kapil      | Ind
1005     | Kapil      | Aus
1006     | Manoj      | NZ
1007     | Manish     | SA
1008     | Paul       | SriLanka
1008     | Paul       | SriLanka
1008     | Paul       | SriLanka
1004     | David      | SA
1005     | David      | SA

我想从给定的表中运行查询,找出代表多个国家/地区的PlayerIDsPlayerNames。例如,PlayerID=1001代表了多个国家/地区,即“IND”和“USA”。 此表中有一些重复的行,但请忽略它们。

3 个答案:

答案 0 :(得分:4)

我认为你的意思是:

SELECT PlayerID, PlayerName
FROM yourTable
GROUP BY PlayerID, PlayerName
HAVING COUNT(DISTINCT Country) > 1;

答案 1 :(得分:1)

避免子查询,CTE,联接,交叉申请等 - 可以尝试像

这样的东西
SELECT Y.PlayerId, Y.PlayerName,COUNT(DISTINCT Y.Country) countriesPlayedFor
       FROM YourTable Y 
            GROUP BY Y.PlayerId, Y.PlayerName
                HAVING COUNT(DISTINCT Y.Country) > 1

答案 2 :(得分:0)

这也将处理重复:

WITH CTE
AS (
    SELECT DISTINCT PlayerID
        ,PlayerName
        ,Country
    FROM dbo.PlayerCountries
    )
SELECT PlayerName
    ,COUNT(Country)
FROM CTE
GROUP BY PlayerName
HAVING COUNT(Country) > 1