SQL查找重复项

时间:2016-05-31 09:20:11

标签: sql sql-server-2008 duplicates

我有一个表格( mytable ),我需要在 value_id 列中找到 master_id ,其中包含null和not null值

master_id  value_id
1          1
1          2
1          1
2          1
2          null
3          null
3          null 

在上面的示例中,我需要获取 master_id = 2,因为包含 null且不是null value_id。 master_id = 1没问题

我怎样才能做到这一点?我正在使用SQL Server 2005 / 2008R2

感谢名单

2 个答案:

答案 0 :(得分:2)

使用GROUP BY / HAVINGcount(*)将计算master_id的所有行,count(value_id)将计算value_id不为null的行。

select master_id
from mytable
group by master_id
having count(*) <> count(value_id) and count(value_id) > 0

执行示例:

SQL>create table mytable (master_id int, value_id int);
SQL>insert into mytable values (1,1);
SQL>insert into mytable values (1,2);
SQL>insert into mytable values (1,1);
SQL>insert into mytable values (2,1);
SQL>insert into mytable values (2,null);
SQL>insert into mytable values (3,null);
SQL>insert into mytable values (3,null);
SQL>select master_id, count(*) totcnt, count(value_id) nonnullcnt
SQL&from mytable
SQL&group by master_id;
  master_id               totcnt           nonnullcnt
=========== ==================== ====================
          1                    3                    3
          2                    2                    1
          3                    2                    0

                  3 rows found

SQL>select master_id
SQL&from mytable
SQL&group by master_id
SQL&having count(*) <> count(value_id) and count(value_id) > 0;
  master_id
===========
          2

                  1 row found

派生表格版本:

select master_id
from
(
    select master_id,
           count(case when value_id is not null then 1 end) as nn,
           count(case when value_id is null then 1 end) as n
    from mytable
    group by master_id
)
where nn > 0 and n > 0

执行为:

SQL>select master_id
SQL&from
SQL&(
SQL&    select master_id,
SQL&           count(case when value_id is not null then 1 end) as nn,
SQL&           count(case when value_id is null then 1 end) as n
SQL&    from mytable
SQL&    group by master_id
SQL&)
SQL&where nn > 0 and n > 0;
  master_id
===========
          2

                  1 row found

答案 1 :(得分:1)

@jarlh建议的解决方案是正确的,也是可取的,或者您也可以在SQL下面使用:

SELECT  T.master_id
FROM    ( SELECT    master_id
          FROM      YourTable
          WHERE     value_id IS NOT NULL
          GROUP BY  master_id
        ) T
        INNER JOIN ( SELECT master_id
                     FROM   YourTable
                     WHERE  value_id IS NULL
                     GROUP BY master_id
                   ) AS R ON T.master_id = R.master_id