检查组内的值是否存在不一致

时间:2016-04-01 12:39:57

标签: sql sql-server

考虑下表

 document_id    group_id    level
 --------------------------------
 1              1           1
 2              1           1
 3              2           3
 4              2           3
 5              2           2
 6              3           1
 7              4           6
 8              4           6
 9              4           6
10              5           2
11              5           1

我想检查一个level中的group_id个文档是否一致,如果不一致,则显示这些组。因此,对于上面的示例,输出必须是:

 document_id    group_id    level
 --------------------------------
 3              2           3
 4              2           3
 5              2           2
10              5           2
11              5           1

我怎样才能做到这一点?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

使用EXISTS查找这些行,其中相同的group_id具有不一致的级别值:

select document_id, group_id, level
from tablename t1
where exists (select 1 from tablename t2
              where t2.group_id = t1.group_id
                and t2.level <> t1.level)

这就是它的执行方式:

SQL>create table t (document_id int, group_id int, level int);
SQL>insert into t values( 1, 1, 1);
SQL>insert into t values( 2, 1, 1);
SQL>insert into t values( 3, 2, 3);
SQL>insert into t values( 4, 2, 3);
SQL>insert into t values( 5, 2, 2);
SQL>insert into t values( 6, 3, 1);
SQL>insert into t values( 7, 4, 6);
SQL>insert into t values( 8, 4, 6);
SQL>insert into t values( 9, 4, 6);
SQL>insert into t values(10, 5, 2);
SQL>insert into t values(11, 5, 1);
SQL>select document_id, group_id, level
SQL&from t t1
SQL&where exists (select 1 from t t2
SQL&              where t2.group_id = t1.group_id
SQL&                and t2.level <> t1.level);
document_id    group_id       level
=========== =========== ===========
          3           2           3
          4           2           3
          5           2           2
         10           5           2
         11           5           1

                  5 rows found

与问题中指定的结果相同。

答案 1 :(得分:1)

修改了jarlh的答案,使查询结果与OP的期望输出相匹配:

使用EXISTS查找这些行,其中同一组也有另一个级别:

select document_id, group_id, level
from tablename t1
where exists (select 1 from tablename t2
              where t2.level <> t1.level
                and t2.group_id = t1.group_id)

答案 2 :(得分:1)

作为exists的替代方案,您可以使用窗口功能:

select document_id, group_id, level
from (select t.*, min(level) over (partition by group_id) as minlevel,
             max(level) over (partition by group_id) as maxlevel
      from t
     ) t
where minlevel <> maxlevel;