自连接后以相反的顺序删除相同的记录

时间:2014-07-30 15:04:34

标签: sql sql-server

我试图将这两行并排放在一行,所以我做了一个内连接

;WITH data AS 
(
    SELECT 1 id, 'a' AS c1 UNION ALL
    SELECT 1 id, 'b' AS c1
)
SELECT *
FROM data d
INNER JOIN data d2
    ON d.id = d2.id
    AND d.c1 <> d2.c1

这会返回两个行,a-b和b-a,它们基本相同,但顺序相反。我怎样才能删除这个准重复?

-- expected results would be just one row (1, a, b)
SELECT 1 d1_id, 'a' AS d1_c1, 'b' AS d2_c1

注意,可能有两个以上的记录共享相同的ID。例如,

SELECT 1 id, 'a' AS c1 UNION ALL
SELECT 1 id, 'b' AS c1 union all
SELECT 1 id, 'c' AS c1 

sql server 2012

编辑:刚想通了。 Row_number会得到我需要的东西。

;WITH data AS 
(
    SELECT *
        ,ROW_NUMBER() OVER(PARTITION BY id ORDER BY c1) rn
    FROM (
    SELECT 1 id, 'a' AS c1 UNION ALL
    SELECT 1 id, 'b' AS c1 union ALL
    SELECT 1 id, 'c' AS c1 
        ) z
)
SELECT *
FROM data d
INNER JOIN data d2
    ON d.id = d2.id
    AND d.c1 <> d2.c1
WHERE d.rn = 1

2 个答案:

答案 0 :(得分:2)

@Gabe,这会有用吗?

DECLARE @Table TABLE (Col1 VARCHAR(10), Col2 VARCHAR(10))

INSERT  @Table
VALUES  ('B', 'A')
        ,('A', 'B')
        ,('D', 'C')
        ,('C', 'D')
        ,('DD', 'CC')
        ,('CC', 'DD')
        ,('DA', 'CB')
        ,('CA', 'DB')

SELECT  t1.Col1
        ,t1.Col2
FROM @Table AS t1
    LEFT OUTER JOIN @Table AS t2
    ON t1.Col1 = t2.Col2
    AND t1.Col2 = t2.Col1
WHERE   t2.Col1 IS NULL
      OR t1.Col1 < t2.Col1

答案 1 :(得分:0)

;WITH data AS 
(
    SELECT 1 id, 'a' AS c1 UNION ALL
    SELECT 1 id, 'b' AS c1 UNION ALL
    SELECT 1 id, 'C' AS C1 
),Data1 AS
(
SELECT ROW_NUMBER()OVER (PARTITION BY d.ID ORDER BY d2.ID DESC)AS RN,d.id,d.c1,d2.id As ID1,d2.c1 As C2
FROM data d
INNER JOIN data d2
    ON d.id = d2.id
    AND d.c1 <> d2.c1

),REsult AS
    (
    Select CASE WHEN ISNULL(ASCII(d.id),0)< ISNULL(ASCII(d.id1),0) THEN d.c2 ELSE d.c1 END Col1,
     CASE WHEN ISNULL(ASCII(d.id),0)> ISNULL(ASCII(d.id1),0) THEN d.c1 ELSE d.c2 END Col2,
     ROW_NUMBER()OVER (PARTITION BY d.ID ORDER BY d.ID DESC)AS RN FROM Data1 d )

SELECT  
         t1.Col1
        ,t1.Col2
FROM REsult AS t1
    LEFT JOIN REsult AS t2
    ON t1.Col1 = t2.Col2
    AND t1.Col2 = t2.Col1
WHERE   t2.Col1 IS NULL
      OR t1.Col1 < t2.Col1