Find previous date based off one from another column and grouped by

Viewed 21

Bit of a hard one to explain, but basically I have table of orders, T1 for example:

---------------x---------x--------------x-----------------x
  customer id  |  item   |  order date  |  recieved date  | 
---------------x---------x--------------x-----------------x
    1          |  Shoes  |  01/12/2020  |   20/12/2020    |
    1          |  Bag    |  22/12/2020  |   31/12/2020    |
    1          |  Bag    |  05/01/2021  |   15/01/2021    |
    1          |  Hat    |  07/04/2021  |   28/04/2021    |
    2          |  Bag    |  04/06/2020  |   14/06/2020    |
    3          |  Shoes  |  01/01/2022  |   11/01/2022    |
    3          |  Bag    |  02/03/2022  |   23/03/2022    |
    3          |  Watch  |  28/03/2022  |   05/08/2022    |
    3          |  Bag    |  01/06/2022  |   13/06/2022    |
---------------x---------x--------------x-----------------x

Now say I want to find for every order of "Bags", what the last item the customer had received was and when (so as to look at which item they last received which may have influenced them to make the next purchase), so the resultant table would be something like:

---------------x---------x--------------x--------------------------x-----------------------x
  customer id  |  item   |  order date  |  Previous Item Received  | Prev Item Received Dt |
---------------x---------x--------------x--------------------------x-----------------------x
    1          |  Bag    |  22/12/2020  |    Shoes                 |   20/12/2020          |
    1          |  Bag    |  05/01/2021  |    Bag                   |   31/12/2020          |
    2          |  Bag    |  04/06/2020  |    NULL                  |   NULL                |
    3          |  Bag    |  02/03/2022  |    Shoes                 |   11/01/2022          | 
    3          |  Bag    |  01/06/2022  |    Bag                   |   23/03/2022          |
---------------x---------x--------------x--------------------------x------------------------x

So if a customer orders an particular item, I want to find what their last received item was before that order was made, and what date it was received on.

0 Answers
Related