搜索重复值并显示它们的上下文
Search duplicated values and show their context
我不确定这个问题的解决方案是否非常简单,或者在纯粹的情况下是不可能的 SQL。
我有一个简单的 table,有 2 列
Number Text
1 a
1 b
2 m
3 x
3 y
3 z
现在的任务是:
搜索所有重复的数字并显示使用这些重复数字的“文本”。
我们看到:1 被使用了两次(与 a 和 b),3 与 x 和 y 和 z 一起使用。但是没有一行是完全重复的。
编辑:
所以我期待这样的事情。
Dup_Num Text
1 a
1 b
3 x
3 y
3 z
搜索副本很容易,但我不知道如何连接“文本”,因为当我将“文本”添加到 SELECT 时,我必须将它用于GROUP,这不会重复..
感谢您在糟糕的一天提供帮助..
在您的情况下,您可能希望使用 LISTAGG 对这些值及其与另一列的关系进行分组
SQL> with result
as (
select '1' as c1 , 'a' as c2 from dual union all
select '1' as c1 , 'b' as c2 from dual union all
select '2' as c1 , 'm' as c2 from dual union all
select '3' as c1 , 'x' as c2 from dual union all
select '3' as c1 , 'y' as c2 from dual union all
select '3' as c1 , 'z' as c2 from dual )
select c1, listagg(c2,',') within group(order by c1) as c3 from result
group by c1;
C C3
- --------------------
1 a,b
2 m
3 x,y,z
SQL>
在 SQL 中查找重复项的规范方法是 self join。
在你的example中:
select s1.*
from stuff s1
inner join stuff s2
on s1.number = s2.number
and s1.text <> s2.text
如果我没理解错的话,你可以用exists
:
select t.*
from t
where exists (select 1 from t t2 where t2.number = t.number and t2.text <> t.text)
order by t.number;
为了性能,您需要 (number, text)
上的索引。
这也可能对您有所帮助。
select * from t where Number in
(select Number from t group by Number having count(*) > 1)
order by Text
我不确定这个问题的解决方案是否非常简单,或者在纯粹的情况下是不可能的 SQL。
我有一个简单的 table,有 2 列
Number Text
1 a
1 b
2 m
3 x
3 y
3 z
现在的任务是: 搜索所有重复的数字并显示使用这些重复数字的“文本”。
我们看到:1 被使用了两次(与 a 和 b),3 与 x 和 y 和 z 一起使用。但是没有一行是完全重复的。
编辑: 所以我期待这样的事情。
Dup_Num Text
1 a
1 b
3 x
3 y
3 z
搜索副本很容易,但我不知道如何连接“文本”,因为当我将“文本”添加到 SELECT 时,我必须将它用于GROUP,这不会重复..
感谢您在糟糕的一天提供帮助..
在您的情况下,您可能希望使用 LISTAGG 对这些值及其与另一列的关系进行分组
SQL> with result
as (
select '1' as c1 , 'a' as c2 from dual union all
select '1' as c1 , 'b' as c2 from dual union all
select '2' as c1 , 'm' as c2 from dual union all
select '3' as c1 , 'x' as c2 from dual union all
select '3' as c1 , 'y' as c2 from dual union all
select '3' as c1 , 'z' as c2 from dual )
select c1, listagg(c2,',') within group(order by c1) as c3 from result
group by c1;
C C3
- --------------------
1 a,b
2 m
3 x,y,z
SQL>
在 SQL 中查找重复项的规范方法是 self join。
在你的example中:
select s1.*
from stuff s1
inner join stuff s2
on s1.number = s2.number
and s1.text <> s2.text
如果我没理解错的话,你可以用exists
:
select t.*
from t
where exists (select 1 from t t2 where t2.number = t.number and t2.text <> t.text)
order by t.number;
为了性能,您需要 (number, text)
上的索引。
这也可能对您有所帮助。
select * from t where Number in
(select Number from t group by Number having count(*) > 1)
order by Text