2017-04-26 81 views
1

問題!我試圖列出所有書籍及其相應的圖書主題,平均成本和常規成本。查找某些組的AVG的相關子查詢

到目前爲止,我查詢...

SELECT BOOK_SUBJECT, AVG(BOOK_COST) 
FROM BOOK 
GROUP BY BOOK_SUBJECT 

該查詢給了我四組總成本的平均。 Final out put should look like this我需要攜帶BOOK_NUM,BOOK_TITLE,BOOK_SUBJECT, BOOK_COST,但我無法弄清楚。有人可以幫忙嗎?相關的子查詢?

+0

您是否使用SQL-Server,MySQL發,還是其他什麼東西?請爲您正在使用的內容添加標籤,但不要添加其他標籤。 – toonice

+0

您還應該包括書籍表的完整結構(以及其加入的任何其他表)。否則答案將是純粹的猜測 – StevieG

回答

0

請嘗試以下...

SELECT BOOK_NUM AS Number, 
     BOOK_TITLE AS Title, 
     BOOK.BOOK_SUBJECT AS Subject, 
     BOOK_COST AS Cost, 
     AVG_BOOK_COST AS 'Avg Cost' 
FROM BOOK 
JOIN (SELECT BOOK_SUBJECT AS BOOK_SUBJECT, 
       AVG(BOOK_COST) AS AVG_BOOK_COST 
     FROM BOOK 
     GROUP BY BOOK_SUBJECT 
    ) AS SUBJECT_AVG_FINDER ON BOOK.BOOK_SUBJECT = SUBJECT_AVG_FINDER.BOOK_SUBJECT 
ORDER BY BOOK_NUM; 

計算平均爲我們的BOOK_SUBJECT並有一批BOOK內容的每個主題使用AVG(BOOK_COST)找到每個組的平均值。但是我們也希望避免將BOOK中的其他字段進行分組,而不是將Book中每條記錄的指定字段與它們的BOOK_SUBJECT的平均成本加在一起顯示。這表明在BOOK和用於查找每個主題的平均成本的子查詢之間的INNER JOIN

我用下面的代碼找到在BOOK列出的每個科目的平均平均成本...

SELECT BOOK_SUBJECT AS BOOK_SUBJECT, 
     AVG(BOOK_COST) AS AVG_BOOK_COST 
FROM BOOK 
GROUP BY BOOK_SUBJECT 

我們需要選擇BOOK_SUBJECT部分原因是GROUP BY條款需要它,部分是因爲我們需要它將此子查詢生成的表加入BOOK的未分組列表中。

給予AVG(BOOK_COST)AVG_BOOK_COST的別名使得引用此生成的字段變得更容易。

在沒有連接類型JOIN之前,大多數版本的SQL將假定爲INNER JOIN,儘管所有允許使用INNER JOIN都可以使用,有些需要您這樣做。默認情況下,我和其他許多人只是使用JOIN

一旦執行從BOOK每條記錄​​將有一個副本的它的相應的從我們的子查詢記錄(這是我給的SUBJECT_AVG_FINDER別名),離開聯同兩個字段每條記錄稱爲BOOK_SUBJECT。爲了不混淆你的SQL版本,我們必須在總體語句的第三行中指定表/子查詢以及發生此類重複的字段名稱,因此BOOK.BOOK_SUBJECT

根據您想要的最終輸出圖像,每個字段都有一個別名。

我假定沒有必要複製行號字段。如果這不正確,請另行說明。

最後,我已經根據您的期望輸出對結果進行了排序,添加了行ORDER BY BOOK_NUM

作爲一個提示,雖然它是允許的,你應該避免使用呼喊(即,全部大寫)你的字段名稱,表名和別名(除非你被要求這樣做),但仍然喊SQL的東西(如SELECT,FROM,AS等)。通過提供關於如何嘗試使用每個單詞的視覺線索,這可以使語句更易於閱讀和調試。我建議展示我們的SQL語句,而不是下面的方式...

SELECT book_num AS Number, 
     book_title AS Title, 
     book.book_subject AS Subject, 
     book_cost AS Cost, 
     avg_book_cost AS 'Avg Cost' 
FROM book 
JOIN (SELECT book_subject AS book_subject, 
       AVG(book_cost) AS avg_book_cost 
     FROM book 
     GROUP BY book_subject 
    ) AS subject_avg_finder ON book.book_subject = subject_avg_finder.book_subject 
ORDER BY book_num; 

如果您有任何問題或意見,然後請隨時據此發佈評論。

0

使用子查詢做到這一點:

SELECT BOOK.BOOK_NUM, BOOK.BOOK_TITLE, BOOK.BOOK_SUBJECT, BOOK.BOOK_COST, T.AVG_COST 
FROM BOOK 
INNER JOIN (
    SELECT BOOK_SUBJECT, AVG(BOOK_COST) AVG_COST 
    FROM BOOK 
    GROUP BY BOOK_SUBJECT 
) T ON BOOK.BOOK_SUBJECT = T.BOOK_SUBJECT 
0

使用此代碼

SELECT BOOK_NUM, BOOK_TITLE, BOOK_SUBJECT, BOOK_COST, 
AVG(BOOK_COST) OVER(PARTITION BY BOOK_SUBJECT) AS AVG_COST 
FROM BOOK