在表格中查找重复项

时间:2015-12-17 14:32:19

标签: sql sql-server select duplicates

我有一个名为FLOORS的表,其中包含许多重复值

FLOORCODE   FLOORDESC
00          Ground Floor
01          1st Floor
02          2nd Floor
00          Ground Floor
00          NEW Floor

对于只会在使用相同FLOORCODE但具有不同FLOORDESC的情况下返回值的查询,我需要使用哪些代码。 所以在上面的例子中我只想看

FLOORCODE     FLOORDESC
00            Ground Floor
00            NEW Floor

5 个答案:

答案 0 :(得分:3)

DECLARE @t TABLE (
    FLOORCODE CHAR(2),
    FLOORDESC VARCHAR(50)
)

INSERT INTO @t
VALUES
    ('00', 'Ground Floor'),
    ('01', '1st Floor'),
    ('02', '2nd Floor'),
    ('00', 'Ground Floor'),
    ('00', 'NEW Floor')

SELECT DISTINCT t2.FLOORCODE, t2.FLOORDESC
FROM (
    SELECT FLOORCODE
    FROM @t
    GROUP BY FLOORCODE
    HAVING COUNT(DISTINCT FLOORDESC) > 1
) t
JOIN @t t2 ON t.FLOORCODE = t2.FLOORCODE

结果 -

FLOORCODE FLOORDESC
--------- ----------------
00        Ground Floor
00        NEW Floor

答案 1 :(得分:1)

一种简单的方法是使用窗口函数:

select f.*
from (select f.*, min(floordesc) over (partition by floorcode) as minfd,
             max(floordesc) over (partition by floorcode) as maxfd
      from floors f
     ) f
where minfd <> maxfd;

不使用窗口函数的替代方法可能会使用exists

select f.*
from floors f
where exists (select 1
              from floors f2
              where f2.floorcode = f.floorcode and f2.floordesc <> f.floordesc
             );

请注意,这两项都可以从floors(floorcode, floordesc)上的索引中受益。这两个版本都忽略了NULL值,尽管很容易将其合并到逻辑中。

答案 2 :(得分:0)

您可以使用having子句查找有问题的floorcode,然后使用in子句查找实际行:

SELECT DISTINCT floorcode, floordesc
FROM   floors
WHERE  floorcode IN (SELECT   floorcode
                     FROM     floors
                     GROUP BY floorcode
                     HAVING   COUNT(DISTINCT floordesc) > 1)

答案 3 :(得分:0)

这也可以使用窗口计数来完成:

DECLARE @Test TABLE
(
    FLOORCODE VARCHAR(50),
    FLOORDESC VARCHAR(50)
);

INSERT INTO @Test (FLOORCODE, FLOORDESC)
VALUES ('00', 'Ground Floor')
    , ('01', '1st Floor')
    , ('02', '2nd Floor')
    , ('00', 'Ground Floor')
    , ('00', 'NEW Floor');

SELECT DISTINCT FLOORCODE, FLOORDESC
FROM (
    SELECT FLOORCODE, FLOORDESC, COUNT(*) OVER(PARTITION BY FLOORCODE) AS Cnt
    FROM @Test
    ) AS T
WHERE T.Cnt > 1;

结果:

╔═══════════╦══════════════╗
║ FLOORCODE ║  FLOORDESC   ║
╠═══════════╬══════════════╣
║        00 ║ Ground Floor ║
║        00 ║ NEW Floor    ║
╚═══════════╩══════════════╝

答案 4 :(得分:0)

这可能会这样做

select floorcode, floordesc
from yourtable where floorcode in 
( select floorcode 
  from yourtable
  group by floorcode having count(*) >1 )