2017-04-18 38 views
0

我需要顯示讀者年齡低於平均年齡的每本書。 架構由以下表:在SQL中使用WITH子句時,我得到一個以上的平均值

AUTHOR: ISBN, Name, Lastname; 
BOOK: ISBN, Name, Publisher, Pages, Value, Year; 
EXEMPLAR: Number, Taken (date), Returned (date), ISBN, Reader (reader's number), READER: Number (also reader's number, just named differently), ID number, Name, Lastname, Birthdate, Address. 

我寫了下面的代碼:

WITH Name_and_age (Age, Name, ISBN) as (SELECT age(birthdate) as Age, Book.ISBN, Name 
FROM Reader 
JOIN Exemplar on Reader.Number=Exemplar.Reader JOIN Book ON Book.ISBN=Exemplar.ISBN), 

MeanAge (Average) 
as (SELECT AVG(Age) as MeanAge FROM Name_and_age) 

SELECT Age, MeanAge, Name, ISBN FROM Name_and_age, MeanAge 
WHERE Age < MeanAge 

但對於一些書,結果顯示:2或3點不同年齡的平均值。唯一書籍的總數是7,但結果給了我10行。有任何想法嗎?先謝謝你!

+0

SELECT age(birthdate)作爲年齡,Book.ISBN,名稱 FROM Reader JOIN Exemplar on Reader.Number = Exemplar.Reader JOIN Book ON Book.ISBN = Exemplar.ISBN'我懷疑它是10.我的猜測是,根據'Reader',或者每個'Exemplar',你有多於一個'Examplar'或者多於一個'Book'。 – JNevill

+0

我不相信這是有效的 - 在第二個表格中,您定義了MeanAge列平均值。但是在最後一個查詢中,您搜索名爲MeanAge的列。也許最後一行應該是WHERE Age Hogan

+0

@JNevill你是對的,有7本獨特的書,8個閱讀器,但是結果表由10行組成。 – Kristupas

回答

0

你說,I need to show every book whose reader's age is below the mean age

代碼包括這樣的:

SELECT Age, MeanAge, Name, ISBN 

你沒有說你想要的年齡。如果是這種情況,請不要選擇它。另外,使用單詞distinct來考慮多個人閱讀的書籍。換句話說,更改上面的代碼如下:

SELECT distinct MeanAge, Name, ISBN 

你也可能要改變這一點:

SELECT AVG(Age) as MeanAge 

這個

SELECT floor(AVG(Age)) as MeanAge 

這將鑄就MeanAge整數並確保如果平均年齡爲15.5歲,則15歲的人將被排除在結果之外。

+0

實際上,我必須在滿足條件的每本書旁邊添加年齡平均值。 – Kristupas