sql只有满足条件时才选择查询

问题描述:

在MS Access中,我有一个两列表(出版物),其中包括作者姓名和他们发表文章的年份。 笔者一年 戴维斯1973年 博伊德乙1973年 戴维斯1974年 坑大号1974年 ... 我想要检索作家谁只在一个特定年份或两个给定的年份,而不是在任何一年发布。例如仅在1973年发表文章并且没有在任何其他年份发表文章的作者。以下查询不会给我:sql只有满足条件时才选择查询

Select authors, year from publications where year = 1973 

这给了那些谁在1973年出版,但他们可能也出版了其他年份。可以用Case来完成吗?应该怎么做?谢谢。

您可以使用此查询获取指定年份中只有一个发布的所有作者。

Select authors, year from publications where year = 1973 
group by authors, year 
having count (year) = 1 

为了让所有的作者只有一个发布,但如果你知道这一年:

Select authors, year from publications where year = 1973 
and authors not in (
select authors from publications where year <> 1973 
) 

如果你不知道的一年,但你要只有一个出版物的所有作者:

Select authors, year from publications where authors not in (
select authors from publications 
group by authors 
having count (authors) = 1 
) 
+0

感谢。这适用于你说的。它给了我作者在给定年份只发表一篇文章,但其中一些发表了其他年份的文章。这不是我想要的。我希望那些仅在一年内发表的文章, – Hamid 2015-03-31 14:12:53

+0

@哈米德我编辑了答案,我希望这对你有用。 – Santiago 2015-03-31 14:43:41

我会留连接到一个子查询,其中包含所有其他出版物不属于那一年,并过滤掉所有记录,因此加入连接

Select p.authors, p.year 
From Publications p 
    left join (Select * 
       From Publications 
       Where Year <> '1973') a on a.authors = p.authors 
Where p.year = '1973' 
     and a.name is null 

现在加入Authorscolumn并不理想,但没有任何主键只能这样做。

如果我正确地理解了您,您想选择仅在特定时间段内发布的作者。

select Author, Published 
From Publications A 
Where Published between @fr and @to 
and not (exists select 'x' from Publications B where A.Author = B.Author and B.Published not between @fr and @to) Group By Author, Published 

如果参数@fr和@至是年,你有兴趣