相关子查询以查找某些组的AVG

时间:2017-04-26 02:00:28

标签: sql correlated-subquery

问题!我正在尝试列出所有书籍及其相应的图书主题,平均成本和常规费用。

到目前为止,我的查询是......

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

此查询为我提供了四组总费用的平均值。 Final out put should look like this我需要引入BOOK_NUMBOOK_TITLEBOOK_SUBJECTBOOK_COST,但我无法弄明白。有人可以帮忙吗?相关子查询?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

要计算每个主题的平均值,我们必须按BOOKBOOK_SUBJECT的内容进行分组,然后使用AVG( BOOK_COST )查找每个组的平均值。但我们也希望避免在BOOK中对其他字段进行分组,而是显示Book中每条记录的指定字段,并在最后添加BOOK_SUBJECT的平均成本。这表明在INNER JOIN和子查询之间BOOK,用于查找每个主题的平均费用。

我使用以下代码查找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的未分组列表。< / p>

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行来按照您想要的输出对结果进行排序。

作为提示,虽然允许,但您应该避免使用喊叫(即全大写)您的字段名称,表名称和别名&#39; (除非你被要求这样做),但仍然大喊SQL的东西(如SELECTFROMAS等)。通过提供关于如何使用每个单词的直观线索,这可以使语句更容易阅读和调试。我建议用以下方式呈现我们的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;

如果您有任何问题或意见,请随时发表评论。

答案 2 :(得分:0)

使用此代码

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