sql - 如何从表中仅选择字段 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 的行。
逻辑如下:
对于 field1 中的每个值,构建一个包含 field1 中所有值的列表,并为每个值构建一个包含它与来自 field2 一起出现的所有值的列表,因此在我们的例子中它将是:
{a : alex, b: joe, alex, c: joe, d: cloe}
查看每个 field1 值的所有列表并检查是否有超过 1 个项目
b : joe, alex
返回具有此类字段 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
)
解决方案
您的样本数据建议我EXISTS
:
select t.*
from table t
where exists (select 1 from table t1 where t1.field1 = t.field1 and t1.field2 <> t.field2);
推荐阅读
- c# - 使用 WPF 应用程序更新数据库
- azure-data-lake - 使用 Azure Data Lake 的 Presto 查询引擎
- mysql - 在 azure 中使用 java 函数应用程序获取 SSL 和连接错误
- blueprism - 将 Excel 中的宏注入 BluePrism
- swift - Firebase 实时数据库和 Xcode:允许每个用户读取自己的数据而不是所有数据
- android - 如何从另一个领域对象中使用一个领域对象?
- performance-testing - 无法理解 jprofiler 的调用树视图
- android - PreferenceManager.setDefaultValues 不适用于自定义首选项
- python - 如何处理 Django 嵌套模板标签
- mysql - MYSQL:INNER JOIN 与 BIG TABLES 的替代方案(太慢了)