sqloracle

Get most recent of two different records for each group


I would like to find the most recent record for task A and task B for each ID by assign_date. The data is in the format

ID task assignee assign_date
ID1 taskA assignee1 date1
ID1 taskB assignee2 date2
ID1 taskA assignee3 date3
ID1 taskC assignee4 date4
ID2 ..... ......... .....

and I'd like for the final result to be something like

ID assignee_taskA assignee_taskB

where the assignee is the most recent one by the assign_date.

I know there are a lot of solutions for most recent single record within a group but I'm hoping to do this with pivot/conditional aggregation so I don't have to do multiple joins.


Solution

  • Just select the latest row and then do the pivot table.

    WITH data AS (
      SELECT
        id,
        task,
        assignee,
        assign_date,
        ROW_NUMBER() OVER(PARTITION BY id, task ORDER BY assign_date DESC) AS r_n
      FROM source_table
    ),
    
    latest_data AS (
      SELECT * FROM data
      WHERE r_n = 1
    )
    
    SELECT * FROM latest_data
    PIVOT (MAX(assignee) FOR task IN ('taskA', 'taskB'))