Skip to content
Advertisement

Window functions + self join to solve?

I want to display how many days an item was in each stage. We have many items, so just showing one ID for now for simplicity.
For first stage it should be action_date -created time.
For last stage it should be today – last action_date (these are uncompleted tasks, that is why we count fromt oday)
For all other, it’s simply the difference in action_dates.
How do you get from top table to bottom with SQL? Thanks a lot in advance!

enter image description here

Advertisement

Answer

One way uses lead() and union all:

Or a cleaner solution (in my opinion) unpivots the data:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement