前2项优惠,包括所有优惠

时间:2015-07-27 19:23:59

标签: sql oracle stored-procedures oracle11g cursor

有人可以告诉我如何获得如下结果。

使用dense_rank函数,其中rank< = 2将给出前2个优惠。

我也希望得到&total; of_offer'这应该是" offer1'的总和。和' offer2'。当没有offer2(例如:taurus)'总报价'应该是' offer1'和' null'为' 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个优惠。 (Using a pl-sql procedure or cursor to select top 3 rank

3 个答案:

答案 0 :(得分:0)

 with x as 
 (select row_number() over(partition by customer,make order by offer desc) rn,
  customer, make, zipcode, offer from tablename)
 , y as (select customer, make, zipcode, offer from x where rn <=2)
 , z as (select customer, make, zipcode, 
         case when rn = 1 then offer else 0 end as offer_1, 
         case when rn = 2 then offer else 0 end as offer_2 
         from y)
  select customer, make, zipcode, offer_1, offer_2, offer_1+offer_2 total_offer
  from z

这使用递归cte来完成你的任务。

答案 1 :(得分:0)

您最好使用ROW_NUMBER代替DENSE_RANK(可能会返回两行以上)加LEAD来查找第二高的值

select customer, make, zipcode,
    TOP_OFFER1, 
    TOP_OFFER2, 
    TOP_OFFER1 + coalesce(TOP_OFFER2,0) as Total_offer
from
 ( 
   select customer, make, zipcode, 
      offer as TOP_OFFER1, -- max offer
      lead(offer) over (partition by customer, make, zipped
                        order by offer desc) as TOP_OFFER2, -- 2nd highest offer
      row_number() over (partition by customer, make, zipped
                        order by offer desc) as rn
  from tab
 ) dt
where rn = 1 -- only the row with the highest offer

答案 2 :(得分:0)

试试这段代码......

WITH subqueryfactoring AS
  (SELECT customer,
    make ,
    zipcode ,
    offer,
    lead(offer) over (partition BY customer, make , zipcode order by offer DESC) SecondLeadValue,
    row_number() over (partition BY customer, make , zipcode order by offer DESC ) rownumber
  FROM abc1
  )
SELECT customer,
  make ,
  zipcode,
  offer "Top Offer1 ",
  SecondLeadValue "Top offer 2",
  offer + COALESCE(SecondLeadValue,0) "Total Offer"
FROM subqueryfactoring
WHERE rownumber<2;