2015-11-21 8 views
5

2年連続して指揮を執るすべてのディレクターのリストを表示しようとしています。連続して表示される値の表示

次のデータを考える:

Pantomime table: 
Year titleID DirectorID 
2000 1   1 
2001 2   7 
2002 3   7 
2003 4   8 
2004 5   9 
2005 6   9 

これは望ましい結果である:

DirectorID 
    7 
    9 

これは私がこれまで試してみましたクエリであるが、所望の結果を得ることができませんでした。

select distinct a.directorID 
from Pantomime as a 
inner join Pantomime as b on a.year = b.year-1 
         and a.directorID = b.directorID; 

私はインナーを使用していますので、参加し、私たちはよ:あなたは来年の値を持つエントリを参照するために結合を使用して、取得関連のidの明瞭とすることができます

SELECT directorID 
FROM pantomime 
where directorID = directorID+1 
GROUP BY directorID 
+0

2年連続のタイトルですか? – mezmi

+0

連続年。だから本質的に、2001年のディレクターID 7、2002年のディレクターID 7年、2004年のディレクターID 9年、2005年のディレクターID 9 – ShyDonkey

+1

これは単純な参加者です – Strawberry

答えて

3

彼らはB-意味で存在する場合year-1はこのdirectorId

+0

これは私にとって最も優雅な解決策のようです。 – Strawberry

5

一つの方法のために、あなたのテーブルに表示されている場合のみからレコードを取得することはexists使用しています:

select distinct p.directorId 
from pantomine p 
where exists (select 1 
       from pantomine p2 
       where p2.directorId = p.directorId and p2.year = p.year + 1 
      ); 

他の楽しみがありますが、このようなinを使用して、このアイデアにバリアント:

select distinct p.directorId 
from pantomine p 
where p.year in (select p2.year + 1 
       from pantomine p2 
       where p2.directorId = p.directorId 
       ); 

そして、ここでは、すべての(単なる集合)で参加するようなメカニズムを使用していない全く不可解な方法です。

select distinct directorId 
from ((select directorId, year from pantomine) 
     union all 
     (select directorId, year + 1 from pantomine) 
    ) p 
group by directorId, year 
having count(*) = 2; 

これは、とselect distinctを使用する実際にはまれなケースの1つです。

0

はこれを試してみてください、何の結合やサブクエリ、単純なグループ化:

SELECT directorID 
FROM pantomime 
GROUP BY directorID 
HAVING COUNT(*) = 2 
AND MAX(Year) = MIN(Year) + 1 

ここではfiddleではありません。

関連する問題