Sql 查找列上存在差异的类似行
我有这样一个sql表:Sql 查找列上存在差异的类似行,sql,sql-server,Sql,Sql Server,我有这样一个sql表: ID NR Status 1 510 2 2 510 2 3 510 2 . ... . 17 987 2 33 987 3 35 987 2 我想得到那张桌子; 若NR列具有相同的值,而Status列具有不同的值。 所以,我想得到包含17、33和35行的表 我尝试了这个方法,但不起作用: select * from table1 as t1 inner
ID NR Status
1 510 2
2 510 2
3 510 2
. ... .
17 987 2
33 987 3
35 987 2
我想得到那张桌子;
若NR列具有相同的值,而Status列具有不同的值。
所以,我想得到包含17、33和35行的表
我尝试了这个方法,但不起作用:
select * from table1 as t1
inner join table1 t2 ON t1.NR=t2.NR and t1.Status != t2.Status
使用窗口功能:
select
*
from
your_table
having
count(distinct status) over (partition by nr) > 1;
窗口功能v2:
select * from
(select
t.*,
count(distinct status) over (partition by nr) cnt
from
your_table t
) t where cnt > 1;
使用联接:
select t1.*
from your_table t1
inner join (
select nr
from your_table
group by nr
having count(distinct status) > 1
) t2 on t1.nr = t2.nr;
用于:
select *
from your_table t1
where nr in (
select nr
from your_table
group by nr
having count(distinct status) > 1
);
使用存在:
select *
from your_table t1
where exists (
select 1
from your_table t2
where t2.nr = t1.nr
and t1.status <> t2.status
);
为什么您需要nr 35?它有相同的功能status@TheGameiswar,行具有相同的NR,但存在其他状态。为什么不也添加一个exists查询?好了@贾尔赫。如果我想得到相同的NR值和相同的Status值表,该怎么办?因此,表包含1、2和3行@古尔夫
select
*
from
table
where
count(distinct status) over (partition by nr) > 1;