各位大大好!
想請問一下 我有一個select完 表像下面這樣
ID會有很多筆一樣的名稱
例如A B 有多筆資料 與 日期
我只想要取出 距離今天最近的兩筆日期的資料
我該怎們下這個語法呢??
| ID | | DATE |
| -------- | | -------- |
| A | | 2015-06-07 |
| B | | 2015-07-07 |
| A | | 2016-06-07 |
| B | | 2015-06-07 |
| A | | 2017-03-07 |
想要的結果是這樣
| ID | | DATE |
| -------- | | -------- |
| A | | 2017-03-07 |
| A | | 2016-06-07 |
| B | | 2015-07-07 |
| B | | 2015-06-07 |
SELECT ID,DATE
FROM TABLES
WHERE where rownum <=2
ORDER BY DATE DESC
在家裡使用 Postgresql, 把 current_date 換成 Oracle的sysdate 就一樣了.
create table ithelp170622 (
id char(1) not null
, date date not null
);
insert into ithelp170622 values
('A', '2015-06-07'),
('B', '2015-07-07'),
('A', '2016-06-07'),
('B', '2015-06-07'),
('A', '2017-03-07');
with t1 as (
select id
, date
, rank() over(partition by id order by abs(current_date - date)) rnk
from ithelp170622
)
select id
, date
from t1
where rnk <= 2;
id | date
----+------------
A | 2017-03-07
A | 2016-06-07
B | 2015-07-07
B | 2015-06-07
(4 筆資料列)
注意那個abs要使用,這樣不管以後的資料日期與當日,總是差距最小的兩筆.自己體會一下.
幸運叔祝大家幸運喔.
create table so_test (
n varchar2(32),
t date );
insert into so_test values ( 'A' , to_date('07-Jul-2015 12:00:00','DD-Mon-YYYY HH24:Mi:SS') );
insert into so_test values ( 'B' , to_date('07-Jul-2015 12:00:00','DD-Mon-YYYY HH24:Mi:SS') );
insert into so_test values ( 'A' , to_date('07-Jun-2016 12:00:00','DD-Mon-YYYY HH24:Mi:SS') );
insert into so_test values ( 'B' , to_date('07-Jun-2015 12:00:00','DD-Mon-YYYY HH24:Mi:SS') );
insert into so_test values ( 'A' , to_date('07-Mar-2017 12:00:00','DD-Mon-YYYY HH24:Mi:SS') );
select n,t from (
select n, t , rank() over ( partition by n order by t desc) r
from so_test)
where r <= 2;