T-SQL删除重复项

时间:2018-09-17 11:44:22

标签: sql sql-server

我有一个表,其中显示了哪个橄榄球队踢过哪个橄榄球队,该表示例:

[ TeamId1 | TeamId2 ]
[ 1       | 2       ]
[ 1       | 3       ]
[ 3       | 1       ]
[ 3       | 2       ]

我需要查询以省略重复项,但这被视为重复项:

Row 1:    
TeamId1: 4     
TeamId2: 3  

Row 2:
TeamId1: 3  
TeamId2: 4  

在这种情况下,我只想返回第1行,但是有些行中没有重复行。

编辑

希望我的问题和表格示例现在更好。

4 个答案:

答案 0 :(得分:2)

假设每对最多有一行:

SELECT t.*
FROM t
WHERE team1 < team2
UNION ALL
SELECT t.*
FROM t
WHERE team2 > team1 AND
      NOT EXISTS (SELECT 1
                  FROM t t2
                  WHERE t2.team1 = t.team2 AND
                        t2.team2 = t.team1);

答案 1 :(得分:1)

也许这对您有用? 始终将最高的视为Team1,最低的视为Team2。

SELECT DISTINCT 
    CASE Team1 > Team2 THEN Team1
    ELSE Team2 END AS Team1, 
    CASE Team1 < Team2 THEN Team1 
    ELSE Team2 END AS Team2
FROM <yourTable>

答案 2 :(得分:0)

通常的伪代码是团队ID不会以相反的顺序重复,其中T2.TeamId1大于T1.TeamId1

DECLARE @temp TABLE (TeamId1 int, TeamId2 int)
INSERT INTO @temp VALUES (1,2), (1,3), (3,1), (3,2), (4,3), (3,4)

SELECT *
  FROM @temp T1
 WHERE NOT EXISTS (SELECT * 
                     FROM @temp T2 
                    WHERE T2.TeamId2 = T1.TeamId1 
                      AND T2.TeamId1 = T1.TeamId2
                      AND T2.TeamId1 > T1.TeamId1)

产生输出:

TeamId1 TeamId2
1       2
3       1
3       2
4       3

上面的查询也可以解释为左联接,通过左联接条件过滤T2字段为NULL的情况:

SELECT T1.*
  FROM @temp T1 LEFT JOIN @temp T2 ON T2.TeamId2 = T1.TeamId1 
                                  AND T2.TeamId1 = T1.TeamId2
                                  AND T2.TeamId1 > T1.TeamId1
 WHERE T2.TeamId1 IS NULL

答案 3 :(得分:-1)

看看是否可行:

SELECT DISTINCT CASE
                    WHEN TeamId1 > TeamId2 THEN TeamId2
                    ELSE TeamId1
                END TeamId1,
                CASE
                    WHEN TeamId1 > TeamId2 THEN TeamId1
                    ELSE TeamId2
                END TeamId2
FROM foot_ballteam