sqloracle-databasegreatest-n-per-group

Fetch the rows which have the Max value for a column for each distinct value of another column


Table:

UserId, Value, Date.

I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date.

How do I do this in SQL? (Preferably Oracle.)

I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.


Solution

  • This will retrieve all rows for which the my_date column value is equal to the maximum value of my_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows.

    select userid,
           my_date,
           ...
    from
    (
    select userid,
           my_date,
           ...
           max(my_date) over (partition by userid) max_my_date
    from   users
    )
    where my_date = max_my_date
    

    "Analytic functions rock"

    Edit: With regard to the first comment ...

    "using analytic queries and a self-join defeats the purpose of analytic queries"

    There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice.

    "The default window in Oracle is from the first row in the partition to the current one"

    The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified.

    The code works.