簡體   English   中英

sql僅在滿足條件時選擇查詢

[英]sql Select query only when a condition is met

在MS Access中,我有一個兩列的表格(出版物),其中包含作者的姓名和他們發表文章的年份。 作者年份Davis A 1973博伊德B 1973 Davis A 1974 Pit L 1974 ...我想檢索僅在單個給定年份或兩個給定年份發表,而不在任何其他年份發表的作者。 例如,僅在1973年才發表文章而在任何其他年份均未發表文章的作者。 以下查詢並沒有告訴我:

Select authors, year from publications where year = 1973

這給了那些在1973年出版的人,但他們可能也在其他年出版了。 凱斯可以做到嗎? 應該怎么做? 謝謝。

我將讓join進入一個子查詢,該查詢包含該年內所有其他未發布的出版物,並過濾掉進行聯接的所有記錄,因此

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 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
)

如果我對您的理解正確,則希望選擇僅在給定時期內發表的作者。

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和@to是您感興趣的年份

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM