is there any way to write query without subquery?.
i have with:
with test as (
select 1 as user_id, 'sadasdasggg1' as order_id, sysdate - 1 as order_date from dual
union
select 1, 'sadasdasggg2', sysdate - 2 from dual
union
select 1, 'sadasdasggg3', sysdate - 3 from dual
union
select 2, 'sadasdasggg4', sysdate - 4 from dual
)
i excepted to get ORDER_ID and the latest ORDER_DATE by user_id.
SELECT ORDER_ID, ORDER_DATE
FROM (
select s.*, row_number() over(PARTITION BY user_id ORDER BY order_date desc) rn
from test s
) WHERE rn = 1
and it works but i want to find out how to get that result without subquery
2
Answers
In Oracle:
or, from Oracle 12:
Which, for your sample data, both output:
Oracle fiddle
The second option also works in PostgreSQL (from version 13) fiddle
In PostgreSQL you can use values clause and
distinct on
.DB Fiddle