简体   繁体   中英

Oracle SQL group by query

I have below data

Name   ID    Action      Action_Date
A123   234     ADD        21/05/2016
A123   234     DELETE     25/05/2016
A124   235     ADD        21/05/2016
A125   236     DELETE     25/05/2016

Now am trying to get below result

Name    ID   Date_Added     Dated_Deleted
A123    234     21/05/2016    25/05/2016
A124    235     21/05/2016     NULL
A125    236       NULL         25/05/2016

I know I need to group by Name and ID but not quite getting how to get the desired output. Please help

When you are trying to flatten the data, it is called a PIVOT. If you are using Oracle, there is a keyword of that name that could be used, but I prefer the old method of conditionally aggregating (mentioned by @Prdp in a comment). The code will be very simple.

SELECT t.name
      ,t.id
      ,MAX(CASE WHEN t.action = 'ADD' THEN t.action_date END) AS date_added
      ,MAX(CASE WHEN t.action = 'DELETE' THEN t.action_date END) AS date_deleted
  FROM your_table t
 GROUP BY t.name
         ,t.id;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM