我需要顯示讀者年齡低於平均年齡的每本書。 架構由以下表:在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行。有任何想法嗎?先謝謝你!
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
我不相信這是有效的 - 在第二個表格中,您定義了MeanAge列平均值。但是在最後一個查詢中,您搜索名爲MeanAge的列。也許最後一行應該是WHERE Age
Hogan
@JNevill你是對的,有7本獨特的書,8個閱讀器,但是結果表由10行組成。 – Kristupas