按列计算sql组中的总和

时间:2017-07-26 18:06:50

标签: sql oracle

book_id location seller daily_sales order_day    Type
 ABC      1        XYZ   100         2017-05-05   Y
 ABC      1        XYZ   120         2017-05-07   Y
 ABC      1        XYZ   40          2017-02-10   Y
 ABC      1        XYZ   60          2017-02-10   N
 .
 .
 .

我正在尝试计算每个book_id的每日销售总额。所以基本上在上表中,  在2017-02-10这一天,总和将是60 + 40。在其他情况下,它只有100&分别为120.

 SELECT book_id, order_day, (SELECT SUM(daily_sales) from facts groupby order_day, book_id, seller) as daily_sum from facts
 where location = 1 group by book_id, seller, seller, location 

我想我做错了。

2 个答案:

答案 0 :(得分:0)

SELECT book_id, seller, location, order_day, SUM(daily_sales)
FROM facts
GROUP BY book_id, location, order_day

为book_id,seller,location和order_day的每个组合获取daily_sales的总和。

答案 1 :(得分:0)

尝试此查询:

SELECT DISTINCT
  t.*
FROM
(
  SELECT
    t.book_id,
    t.seller,
    t.order_day,
    sum(t.daily_sales) over (partition by t.book_id, t.seller, t.order_day) AS result 
  FROM
    facts t
) t