简体   繁体   中英

sql Select query only when a condition is met

In MS Access I have a two-column table (publications) that includes authors' names and the year they published their articles. author year Davis A 1973 Boyd B 1973 Davis A 1974 Pit L 1974 ... I want to retrieve authors who only publish in a single given year or in two given year and NOT in any other year. For example authors who published articles only in 1973 and did not publish article in any other year. The following query doesn't give me that:

Select authors, year from publications where year = 1973

This gives those who published in 1973 but they might have also published in other years. Can it be done with Case? How should it be done? Thanks.

I would left join to a sub query which contains all their other publications which do not fall into that year and filter off all records where a join was made so

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

Now it's not ideal joining on Authorscolumn but without any primary key only way I could do it.

You can use this query for get all authors with only one publication in the specified year.

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

For get all authors with only one publication but if you know the year:

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

And if you don't know the year but you want all authors with only one publication:

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

If I understand you correctly you want to select authors who have only published in a given period.

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

Where Parameters @fr and @to are the years you are interested in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM