1

I would need some help with below case: My data contains dates of order arrival in one column. enter image description here

I want to add second column what would use date from one row below: enter image description here

1 Answer 1

1

Use lead():

select t.dept, t.date as arrival, t.next_arrival
from (select t.*, lead(date) over (partition by dept order by date) as next_arrival
      from t
     ) t
where t.next_arrival is not null;

If you are happy with all rows in the result set and the next_arrival being NULL, then you don't need the subquery.

Sign up to request clarification or add additional context in comments.

3 Comments

I added a rule for NULL: IFNULL(lead(date) over (partition by dept order by date), '9999-12-31') as next_arrival
@marcin2x4 . . . That has nothing to do with your question, which does not include such a default value. But it is a perfectly legitimate thing to do -- except I would recommend the three-argument form of LEAD() instead.
Yes, I forgot to post this addition to my question. lead(date,1,'999-12-31') is indeed better ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.