有人可以告诉我如何获得如下结果。
使用dense_rank函数,其中rank< = 2将给出前2个优惠。
我也希望得到&total; of_offer'这应该是" offer1'的总和。和' offer2'。当没有offer2(例如:taurus)'总报价'应该是' offer1'和' null'为' offer2'
输入:
customer make zipcode offer
mark focus 101 250
mark focus 101 2500
mark focus 101 1000
mark focus 101 1500
henry 520i 21405 500
henry 520i 21405 100
henry 520i 21405 750
henry 520i 21405 100
mark taurus 48360 250
mark mustang 730 500
mark mustang 730 1000
mark mustang 730 1250
期望的输出:
| CUSTOMER | MAKE | ZIPCODE | TOP_OFFER1 | TOP_OFFER2 | Total_offer |
| henry | 520i | 21405 | 750 | 500 | 1250
| mark | focus | 101 | 2500 | 1500 | 4000
| mark | mustang | 730 | 1250 | 1000 | 2250
| mark | taurus | 48360 | 250 | NULL| 250 |
答案 0 :(得分:0)
试试这个......
select * from (
select customer,make,zipcode,offer, dense_rank() over (PARTITION by customer order by customer,make, zipcode,offer desc) Rank from tablename)
where Rank <4;
答案 1 :(得分:0)
Oracle 11g R2架构设置:
CREATE TABLE TEST ( customer, make, zipcode, offer ) AS
SELECT 'mark', 'focus', 101, 250 FROM DUAL
UNION ALL SELECT 'mark', 'focus', 101, 2500 FROM DUAL
UNION ALL SELECT 'mark', 'focus', 101, 1000 FROM DUAL
UNION ALL SELECT 'mark', 'focus', 101, 1500 FROM DUAL
UNION ALL SELECT 'henry', '520i', 21405, 500 FROM DUAL
UNION ALL SELECT 'henry', '520i', 21405, 100 FROM DUAL
UNION ALL SELECT 'henry', '520i', 21405, 750 FROM DUAL
UNION ALL SELECT 'henry', '520i', 21405, 100 FROM DUAL
UNION ALL SELECT 'mark', 'taurus', 48360, 250 FROM DUAL
UNION ALL SELECT 'mark', 'mustang', 730, 500 FROM DUAL
UNION ALL SELECT 'mark', 'mustang', 730, 1000 FROM DUAL
UNION ALL SELECT 'mark', 'mustang', 730, 1250 FROM DUAL;
查询1 - 如果每组最多需要3行::
WITH ranks AS (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY CUSTOMER, MAKE, ZIPCODE ORDER BY OFFER DESC ) AS RANK
FROM TEST t
)
SELECT *
FROM RANKS
WHERE RANK <= 3
<强> Results 强>:
| CUSTOMER | MAKE | ZIPCODE | OFFER | RANK |
|----------|---------|---------|-------|------|
| henry | 520i | 21405 | 750 | 1 |
| henry | 520i | 21405 | 500 | 2 |
| henry | 520i | 21405 | 100 | 3 |
| mark | focus | 101 | 2500 | 1 |
| mark | focus | 101 | 1500 | 2 |
| mark | focus | 101 | 1000 | 3 |
| mark | mustang | 730 | 1250 | 1 |
| mark | mustang | 730 | 1000 | 2 |
| mark | mustang | 730 | 500 | 3 |
| mark | taurus | 48360 | 250 | 1 |
查询2 - 如果您想要前三个等级,包括关系:
WITH ranks AS (
SELECT t.*,
DENSE_RANK() OVER ( PARTITION BY CUSTOMER, MAKE, ZIPCODE ORDER BY OFFER DESC ) AS RANK
FROM TEST t
)
SELECT *
FROM RANKS
WHERE RANK <= 3
<强> Results 强>:
| CUSTOMER | MAKE | ZIPCODE | OFFER | RANK |
|----------|---------|---------|-------|------|
| henry | 520i | 21405 | 750 | 1 |
| henry | 520i | 21405 | 500 | 2 |
| henry | 520i | 21405 | 100 | 3 |
| henry | 520i | 21405 | 100 | 3 |
| mark | focus | 101 | 2500 | 1 |
| mark | focus | 101 | 1500 | 2 |
| mark | focus | 101 | 1000 | 3 |
| mark | mustang | 730 | 1250 | 1 |
| mark | mustang | 730 | 1000 | 2 |
| mark | mustang | 730 | 500 | 3 |
| mark | taurus | 48360 | 250 | 1 |