2017-01-09 5 views
2

列に違いが同様の行を検索:私はこのような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

をあなたが 'を必要とする理由Nrが35'それは同じNRが、他のステータスが存在すると、行、同じ状態 – TheGameiswar

+0

@TheGameiswarを持っています。 – jarlh

答えて

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

EXISTSクエリも追加してみませんか? – jarlh

+0

そこに行く.. @ jarlh。 。 。 – GurV

+1

素晴らしい! (数分前にそれを見てupvotedしました) – jarlh

1
select 
    * 
from 
    table 
where 
    count(distinct status) over (partition by nr) > 1; 
関連する問題