首页 > 解决方案 > 如何从表中仅选择字段 1 中的值与字段 2 的至少两个不同值配对的行

问题描述

考虑下表:

select * 
from
    (values 
        (1,'a','alex'),
        (2,'b','joe'),
        (3,'b','alex'),
        (4,'c','joe'),
        (5,'a','alex'),
        (6,'d','cloe')
    )as mytable (key_field,field1,field2)

我需要一个查询,它将带有键 2 和 3 的行。

逻辑如下:

  1. 对于 field1 中的每个值,构建一个包含 field1 中所有值的列表,并为每个值构建一个包含它与来自 field2 一起出现的所有值的列表,因此在我们的例子中它将是:

    {a : alex, b: joe, alex, c: joe, d: cloe}
    
  2. 查看每个 field1 值的所有列表并检查是否有超过 1 个项目

    b : joe, alex
    
  3. 返回具有此类字段 1 值的原始数据的唯一键。

    2,3
    

我把它理解为一个代码,但我不知道如何编写一个给我这个结果的 sql 查询?

*************** 由 Yogesh Sharma 解决 ***************

我粘贴完整的解决方案查询以供参考

我为问题添加了一层:查询需要从第 2 阶段返回仅包含给定名称的对。

例如下面的给定名称为“cloe”的数据集应仅返回第 4,9 行。如果给定名称是 'alex',则查询应仅返回 raws 2,3

declare @field2Compulasory as char(16)
set @field2Compulasory = 'cloe'
;
with  CTE1 as
(
    select * 
    from
        (values 
            (1,'a','alex'),
            (2,'b','joe'),
            (3,'b','alex'),
            (4,'c','joe'),
            (5,'a','alex'),
            (6,'d','cloe'),
            (8,'e','bill'),
            (9,'c','cloe'),
            (10,'g','jenifer'),
            (11,'h','fred')
        )as mytable (key_field,field1,field2)
), 
CTE2 as (
select *
from CTE1 as t
where exists    (
                    select t1.field1 
                    from CTE1 as t1 
                    where 1=1 
                        and t1.field1 = t.field1 
                        and t1.field2 <> t.field2               
                )
)
select *
from CTE2 as t
where exists    (
                    select *
                    from CTE2 as t1
                    where 1=1
                        and t1.field1 = t.field1
                        and t1.field2 = @field2Compulasory
                )

标签: sqlsql-servertsql

解决方案


您的样本数据建议我EXISTS

select t.*
from table t
where exists (select 1 from table t1 where t1.field1 = t.field1 and t1.field2 <> t.field2);

推荐阅读