我有一个像这样的SQL表:
ID NR Status
1 510 2
2 510 2
3 510 2
. ... .
17 987 2
33 987 3
35 987 2
我想得到那张桌子; 如果 NR 列具有相同的值且状态列具有不同的值。 所以,我想得到包含17,33和35行的表。
我试试这个,但它不起作用:
select * from table1 as t1
inner join table1 t2 ON t1.NR=t2.NR and t1.Status != t2.Status
答案 0 :(得分:1)
使用窗口函数:
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;
使用IN:
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
);
答案 1 :(得分:1)
select
*
from
table
where
count(distinct status) over (partition by nr) > 1;