【问题标题】:Top 2 offers with sum of all offers with description前 2 个优惠,所有优惠的总和以及描述
【发布时间】:2015-07-28 18:40:15
【问题描述】:

有人可以告诉我如何获得如下结果。 (附描述前 2 名现金优惠)

使用 rank

我也希望得到“total_offer”,它应该是“offer1”和“offer2”的总和。当没有 offer2(例如:taurus)时,'total offer' 应该是 'offer1' 和 'null' for 'offer2'

输入:

customer    make    zipcode offer notes  
mark        focus   101     250   cash  
mark        focus   101     2500  appreciation cash  
mark        focus   101     1000  cash  
mark        focus   101     1500  cash offer  

henry       520i    21405   500  cash offer  
henry       520i    21405   100  cash  
henry       520i    21405   750  appreciation cash  
henry       520i    21405   100  cash  

mark        taurus  48360   250    appreciation cash  

mark        mustang 730     500  cash  
mark        mustang 730     1000  Cash offer  
mark        mustang 730     1250  appreciation cash  

期望的输出:

| CUSTOMER | MAKE    | ZIPCODE | TOP_OFFER1 | NOTES1            | TOP_OFFER2 | NOTES2     | Total_offer   
| henry    | 520i    | 21405   | 750        | appreciation cash | 500        | cash offer | 1250    
| mark     | focus   | 101     | 2500       | appreciation cash | 1500       | cash offer | 4000  
| mark     | mustang | 730     | 1250       | appreciation cash | 1000       | cash offer | 2250    
| mark     | taurus  | 48360   | 250        | appreciation cash | NULL       | 250        |   

谢谢

PS:

下面的链接告诉我需要执行dense_rank 才能获得前2 名的优惠。 (Top 2 offers with sum of all offers)

【问题讨论】:

    标签: sql oracle11g


    【解决方案1】:

    您将使用条件聚合:

    select customer, make, zipcode,
           max(case when seqnum = 1 then offer end) as offer1,
           max(case when seqnum = 1 then notes end) as notes1,
           max(case when seqnum = 2 then offer end) as offer2,
           max(case when seqnum = 2 then notes end) as notes2,
           sum(offer) as total_offer
    from (select t.*,
                 row_number() over (partition by customer, make, zipcode order by offer desc) as seqnum
          from table t
         ) t
    group by customer, make, zipcode;
    

    【讨论】:

    • 输出是 2 行而不是 1 行
    • |亨利 | 520i | 21405 | 750 |升值现金 | 500 |现金优惠 | 1250
    • |亨利 | 520i | 21405 | 750 |升值现金
    • |亨利 | 520i | 21405 | 500 |现金优惠
    • 这没有意义。每个客户/品牌/邮政编码的组合应该只有一行。
    猜你喜欢
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多