有如下一張表Orders
id pdate payno
1 2019-11-02 5
1 2019-11-02 3
1 2019-11-03 1
1 2019-11-03 3
2 2019-11-09 1
2 2019-11-09 4
2 2019-11-08 3
2 2019-11-08 2
查詢出每個發貨單號(shipid),最早付款時間(paydate)和最小付款單號(payno)
結果如下:
id pdate payno
1 2019-11-02 3
2 2019-11-08 2
解決:
select id
,pdate
,payno
from (
select id
,pdate
,payno
,rownumber() over(partition by id,pdate order by payno) as rn
from orders
)a
where rn = 1
;
id pdate payno
1 2019-11-02 3
2 2019-11-08 2
備註:建表和數據
create table orders(id int,pdate date,payno int);
insert into orders values(1,'2019-11-02',5);
insert into orders values(1,'2019-11-02',3);
insert into orders values(1,'2019-11-03',1);
insert into orders values(1,'2019-11-03',3);
insert into orders values(2,'2019-11-09',1);
insert into orders values(2,'2019-11-09',4);
insert into orders values(2,'2019-11-08',3);
insert into orders values(2,'2019-11-08',2);