Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can someone please tell how can I get the results as below.

Using dense_rank function where rank <=2 will give me top 2 offers.

I am also looking to get 'total_offer' which should be sum of 'offer1' and 'offer2'. when there is no offer2 ( eg:taurus) 'total offer' should be 'offer1' and 'null' for 'offer2'

Input:

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  

Desired Output:

| 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 |   

Thanks

PS:

The link below tells me that dense_rank need to be performed to get top 2 offers. (Using a pl-sql procedure or cursor to select top 3 rank)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
256 views
Welcome To Ask or Share your Answers For Others

1 Answer

 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

This makes use of recursive cte's to accomplish your task.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...