2015-11-21 37 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 directorID 
FROM pantomime 
where directorID = directorID+1 
GROUP BY directorID 
+0

连续两年还是头衔? – mezmi

+0

连续几年。所以基本上,2001年directorID 7,2002年directorID 7,2004年directorID 9,2005年directorID 9 – ShyDonkey

+1

这只是一个简单的加入 – Strawberry

回答

3

您可以使用加入,看看哪些条目具有明年的值,然后用不同的获得相关的ID:

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

,因为我使用加盟,我们会从只得到记录,如果他们在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 distinctgroup by的真的,非常罕见的情况之一。

0

试试这个,没有加入或子查询,只是一个简单的分组:

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

这里是一个fiddle