Home > database >  SQL query to show previous data in new column
SQL query to show previous data in new column

Time:11-19

I currently have a table that looks like this:

ClaimID Department Date
ABC12 Sales Jun-12-2020
ABC12 Sales Jul-13-2020
ABC12 Marketing Aug-15-2020
DEF23 IT Jul-13-2020
DEF23 IT Sept-12-2020
DEF23 IT Oct-21-2020
DEF23 Sales Nov-12-2020

I want to be able to look at the date when the Department changes(from Sales to Marketing or IT to Sales in this example) along with the previous department using the ClaimID as a key. This would be an example of what I want to return:

ClaimID Department Date Date Changed Previous
ABC12 Sales Jun-12-2020 N/A N/A
ABC12 Sales Jul-13-2020 N/A N/A
ABC12 Marketing Aug-15-2020 Aug-15-2020 Sales
DEF23 IT Jul-13-2020 N/A N/A
DEF23 IT Sept-12-2020 N/A N/A
DEF23 IT Oct-21-2020 N/A N/A
DEF23 Sales Nov-12-2020 Nov-12-2020 IT

My initial idea is to create a subquery where I order by the ClaimID and then compare the values in the Department column with the previous row. However, I can't wrap my mind around how to do the comparison using SQL. Any help is appreciated!

CodePudding user response:

In MySQL 8 you can use the lag() window function and a CASE expression.

SELECT claimid,
       department,
       date,
       CASE
         WHEN lag(department) OVER w <> department THEN
           date
       END datechanged,
       CASE
         WHEN lag(department) OVER w <> department THEN
           lag(department) OVER w
       END previous
       FROM elbat
       WINDOW w AS (PARTITION BY claimid
                    ORDER BY date)
       ORDER BY claimid,
                date;
  • Related