有人可以告诉我如何获得如下结果。 (描述获得前2名现金优惠)
使用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个优惠。 (Top 2 offers with sum of all offers)
答案 0 :(得分:0)
您将使用条件聚合:
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;