2015-10-08 80 views
0

我有一个表是这样的:SQL选择从同一个表

enter image description here

我想编写输出有两个2000年和2001年只有occurencies记录的查询。

在这种情况下,输出会

Bb 2000 
Bb 2001 

,因为只有一个名为黑板上记录有两年occurencies。

我已经尝试过子查询和连接,但没有成功,因为两列不是主键也不是外键。

谢谢。

+0

如果'Bb'也正好有一个记录'2005',你想要它还是返回,还是只有'2000/2001'记录?或者,那个额外的'2005'记录实际上是否使任何'Bb'行不能完全返回? – sstan

+0

我已经根据@vkp提供的解决方案解决了我的问题。 但是要回答您的问题,我的表格只能在_year_列中具有'2000'或'2001'。没有其他年份会出现。但是,如果_year_有可能具有其他值,那么我希望获得对同一个_name_具有超过一年的记录。 – RodWall

回答

1

您可以使用intersect来做到这一点。

select x.name, x.year from 
(
select name from table where year = 2000 
intersect 
select name from table where year = 2001 
) t join table x on t.name = x.name 
1

我的表只能在year20002001。没有其他年份会出现。但是,如果year可能具有其他值,那么我想要获得同一name已超过一年的记录。

如果你有需要处理与其他年份为您的评论描述,那么这是查询我会用:

select id, name, year 
    from (select id, name, year, 
       count(distinct year) over (partition by name) as distinct_year_cnt 
      from table_name) 
where distinct_year_cnt > 1 
相关问题