如果我想要Oracle SQL到GROUP BY而不是那个怎么办?

时间:2015-09-01 16:32:47

标签: oracle

这是我之前从另一个SQL代码获得的内容:

    Customer Id week_ending Purchase Id Price
    1234    2/28/2015   8604220 15
    1234    2/28/2015   8604220 13.75
    1234    2/28/2015   8604220 12.95
    1234    2/28/2015   8604220 18.95
    567890  8/15/2015   6376243 5.15
    567890  8/15/2015   6376243 0.89
    567890  8/15/2015   6376243 3.99
    567890  8/15/2015   6376243 2.3
    1234    1/24/2015   8824241 0.99
    1234    1/24/2015   8824241 3.99
    1234    1/24/2015   8824241 3.89

现在我想按购买ID加价,因为它对我们客户的每个订单都是唯一的,但我不希望我的SQL根据客户ID进行思考和总结(因为每个客户都可以使用多个购买ID多次订购)。以下是我写的代码,但我担心它会通过customer_id对它们求和。如何避免双重会计错误?提前致谢!

    WITH example AS(SELECT
          customer_id
          ,MAX(nvl(promised_arrival_day, ship_day)) OVER (PARTITION BY purchase_id) AS ship2_day
          ,purchase_id
          ,SUM(price) AS order_size
        FROM
          my_table 

        GROUP BY 
         customer_id
         ,MAX(nvl(promised_arrival_day, ship_day)) OVER (PARTITION BY customer_purchase_id) 
         ,purchase_id)
    SELECT 
    example.customer_id
     ,TO_CHAR(example.ship2_day + (7-TO_CHAR(example.ship2_day,'d')),'MM-DD-YYYY') AS week_ending
   ,example.purchase_id
    ,example.order_size
  FROM 
   example;

2 个答案:

答案 0 :(得分:2)

只需

SELECT customer_id, purchase_id, sum(price)
FROM   your_table
GROUP BY customer_id, purchase_id

每条记录只计算一次。它没有做任何"双重会计"如你所说。

您将在数据中为customer_id / puchase_id的每个唯一组合获得一条记录。

答案 1 :(得分:0)

查看您的数据,我会做类似的事情。

 with tbl as(
      -- query by which you are getting     dataset in example
     )
 select customer_id,purchase_id, sum(price) as total_price from tbl
 group by purchase_id,customer_id