SQL查询场景。

时间:2015-10-28 16:30:15

标签: sql oracle group-by

假设我有下表:

enter image description here

我的目标是显示一个如下所示的选择结果集:

enter image description here

这里棘手的部分是为每本书显示AverageCostPerType列。

我知道如何获取AverageCostPerType,它只是以下内容: SELECT avg(bookcost)as AverageCostPerType FROM BOOK GROUPBY BookType;

这将显示3行,因为我有3种不同的类型。如何显示每本书的平均帐户类型?

我会感激你的帮助。

4 个答案:

答案 0 :(得分:4)

您需要使用analytic functions

AVG per BookType

select b.*, avg(bookcost) over (PARTITION BY BookType)
from book b

所有书籍的AVG

select b.*, avg(bookcost) over ()
from book b

答案 1 :(得分:3)

您可以将aggregate函数与分析分区窗口一起使用,以按书型获取平均成本。

这允许您在不将表连接到自身或使​​用嵌套的select语句的情况下执行查询。

Oracle Aggregate Functions

select Book_num,
    BookType,
    avg(BookCost) over(partition by BookType) as AverageCostPerType,
    BookCost,
    BookCost - avg(BookCost) over(partition by BookType) as Difference
from YourBookTable

答案 2 :(得分:2)

您可以计算派生表中每种书籍类型的平均值,并将join计算到原始表格中以获得结果。

select book_num, t.booktype, x.avgcost, bookcost, x.avgcost-bookcost
from tablename t join 
(select booktype, avg(bookcost) as avgcost from tablename group by booktype) x
on t.booktype = x.booktype 

答案 3 :(得分:0)

select b.*, 
       b2.AverageCostPerType, 
       b2.AverageCostPerType - b.BookCost as difference
from book b
join 
(
  SELECT BookType, avg(bookcost) as AverageCostPerType 
  FROM BOOK 
  GROUP BY BookType
) b2 on b.BookType = b2.BookType