SQL> select * from t1; BILL_NO SPCODE SALE_DATE SALE_NUM
---------- ---------- ---------- ----------
1 501 01-1月 -04 10
1 501 02-1月 -04 15
1 502 03-1月 -04 17
1 502 04-1月 -04 19
1 502 05-1月 -04 21
1 502 06-1月 -04 22
1 502 07-1月 -04 23
1 503 08-1月 -04 24
1 503 09-1月 -04 25
1 503 10-1月 -04 26
1 503 11-1月 -04 27已选择11行。SQL> select
2 bill_no,spcode,sale_date,sale_num
3 from
4 (select bill_no,spcode,sale_date,sale_num,(row_number() over (partition
by bill_no,spcode order by bill_no,spcode,sale_date)) rk from t1)
5 where
6 rk<=3; BILL_NO SPCODE SALE_DATE SALE_NUM
---------- ---------- ---------- ----------
1 501 01-1月 -04 10
1 501 02-1月 -04 15
1 502 03-1月 -04 17
1 502 04-1月 -04 19
1 502 05-1月 -04 21
1 503 08-1月 -04 24
1 503 09-1月 -04 25
1 503 10-1月 -04 26已选择8行。
---------- ---------- ---------- ----------
1 501 01-1月 -04 10
1 501 02-1月 -04 15
1 502 03-1月 -04 17
1 502 04-1月 -04 19
1 502 05-1月 -04 21
1 502 06-1月 -04 22
1 502 07-1月 -04 23
1 503 08-1月 -04 24
1 503 09-1月 -04 25
1 503 10-1月 -04 26
1 503 11-1月 -04 27已选择11行。SQL> select
2 bill_no,spcode,sale_date,sale_num
3 from
4 (select bill_no,spcode,sale_date,sale_num,(row_number() over (partition
by bill_no,spcode order by bill_no,spcode,sale_date)) rk from t1)
5 where
6 rk<=3; BILL_NO SPCODE SALE_DATE SALE_NUM
---------- ---------- ---------- ----------
1 501 01-1月 -04 10
1 501 02-1月 -04 15
1 502 03-1月 -04 17
1 502 04-1月 -04 19
1 502 05-1月 -04 21
1 503 08-1月 -04 24
1 503 09-1月 -04 25
1 503 10-1月 -04 26已选择8行。
bill_no,spcode,sale_date,sale_num
from
(select bill_no,spcode,sale_date,sale_num,
rank () over (partition by spcode order by sale_date desc,bill_no desc) as rank_date
from t1)
where
rank_date <=3;
用oracle的分析函数,注意只有enterprise edition才支持。
rank () over (partition by spcode order by sale_date desc,bill_no desc)
partition by spcode 是以spcode分组,类似于group by.
order by sale_date desc就是以日期的降序排位。
加上bill_no desc是如果某种商品同一天内有4次纪录的话,避免取出3条以上的纪录。