We can use FIRST_VALUE
with DISTINCT
in a subquery and use ROWNUM
to add the rank column:
SELECT "id", "type", startdate, ROWNUM AS rank
FROM
(SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") OVER
(PARTITION BY "type" ORDER BY "start date" DESC) AS startdate
FROM Table1) groupedData;
Beware that this query will - like the queries from the other answers, too - fail in case the date column can be NULL
!
To avoid that, we can add an IGNORE NULLS
clause:
SELECT "id", "type", startdate, ROWNUM AS rank
FROM
(SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") IGNORE NULLS OVER
(PARTITION BY "type" ORDER BY "start date" DESC
ROWS BETWEEN unbounded preceding AND unbounded following) AS startdate
FROM Table1) groupedData;
I don't know if that "rank" column in your description already holds the correct row number information and can safely be used for that or if this is not possible or too risky.
If it can be used for that, there is no need for a subquery to fetch the row number. Again the two options with or without ignoring NULL
values:
SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") OVER
(PARTITION BY "type" ORDER BY "start date" DESC ) AS startdate,
"rank"
FROM Table1
ORDER BY "id", "type", "rank";
OR
SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") IGNORE NULLS OVER
(PARTITION BY "type" ORDER BY "start date" DESC
ROWS BETWEEN unbounded preceding AND unbounded following) AS startdate,
"rank"
FROM Table1
ORDER BY "id", "type", "rank";