i have a table my_date
id Start END 1 2021-01-13 2021-04-15 1 2021-04-16 2021-11-28 1 2021-11-29 null 2 2021-05-05 2021-09-13 2 2021-09-13 2021-12-31 3 2020-01-09 2021-08-29 3 2021-08-30 2023-04-15
what i want to want to choose the id that have max(end)<= 2021-12-31 so my result should be just
id Start END 2 2021-09-13 2021-12-31
You can filter by the date limit, then order by date in descending manner, and finally retrieve the first row only.
For example:
select *
from t
where end <= date '2021-12-31'
order by end desc
fetch next 1 rows only
Result:
ID START END
-- ---------- ----------
2 2021-09-13 2021-12-31
See running example at db<>fiddle .
Try this:
SELECT id, Start, END
FROM
(
SELECT *
, ROW_NUMBER () OVER (PARTITION BY ID ORDER BY Start DESC) AS RN_
FROM
(
VALUES
(1, '2021-01-13', '2021-04-15')
, (1, '2021-04-16', '2021-11-28')
, (1, '2021-11-29', null)
, (2, '2021-05-05', '2021-09-13')
, (2, '2021-09-13', '2021-12-31')
, (3, '2020-01-09', '2021-08-29')
, (3, '2021-08-30', '2023-04-15')
) T (id, Start, END)
) T
WHERE RN_ = 1 AND END <= '2021-12-31'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.