2015-09-27 50 views
0

請注意,我剛剛開始學習PostgreSQL,因爲大學和英語不是我的母語。獲得行數最多的年份

我需要找到發行書籍最受歡迎的年份(發行最多的時候發行的書籍年份)。

在這裏我得到分三年按這本書被釋放和複製副本的數量:

Select distinct book.year, count(copy.nr) 
From stud.book, stud.copy 
Where copy.taken is not null and book.isbn=copy.isbn 
Group by book.year; 

這就是我得到:

year | count 
------+------- 
2007 |  2 
2006 |  9 
2005 |  5 
(3 rows) 

這是我真正需要的:

year | count 
------+------- 
2006 |  9 

因爲在2006年發佈書籍最受歡迎(9份,分別採取的書,我發佈n 2006)。

+0

您需要定義如何打破關係:如果您碰巧得到多於一個的最大計數,應選擇哪一年? –

回答

2

使用order bylimit 1

Select book.year, count(copy.nr) as cnt 
From stud.book, stud.copy 
Where copy.taken is not null and book.isbn=copy.isbn 
Group by book.year 
Order by cnt desc 
Limit 1; 

注:請不要使用distinctgroup by,除非你真的知道自己在做什麼。另外,表的別名和明確join語法更容易做出這樣的查詢寫入和讀取:

Select b.year, count(c.nr) as cnt 
From stud.book b join 
    stud.copy c 
    on b.isbn = c.isbn 
Where c.taken is not null 
Group by b.year 
Order by cnt desc 
Limit 1; 

一個簡單的法則:from子句中決不使用逗號; 始終使用使用明確的join語法。

+0

對於這個特定的練習,我不能使用像LIMIT這樣的非標準函數......但是,謝謝你,這個例子有助於更好地理解它。 – Pa2k3l1s

+1

然後使用ANSI標準'FETCH FIRST 1 ROW ONLY'。 Postgres也支持這一點。 (我認爲人們傾向於選擇'LIMIT',因爲它更容易打字。) –

+0

謝謝你的幫助! – Pa2k3l1s

0

您應該使用適當的連接語法,而不是在where子句中聲明join條件。

這樣做的一種方法是使用cte

with counts as (
select book.year, count(copy.nr) as cnt 
from stud.book join stud.copy 
on book.isbn=copy.isbn 
where copy.taken is not null 
group by book.year) 
select * from counts 
where cnt = (select max(cnt) as maxcnt from counts) 
+0

非常感謝!奇蹟般有效 :) – Pa2k3l1s

相關問題