I have a table with the following information:
Data Sample
**Table 1**
palletNumber-- event-- --recordDate
-----1-----------A-------01/11/2015 01:00
-----1-----------B-------01/11/2015 02:00
-----1-----------C-------01/11/2015 03:00
-----1-----------D-------01/11/2015 04:00
-----2-----------A-------01/11/2015 01:10
-----2-----------C-------01/11/2015 01:15
-----2-----------E-------01/11/2015 01:20
I want to select all the possible combinations of events that appear in the table in the sequence of the recordDate by palletNumber. I tried various statements with Row Number, Over Partition but this did not get me close to what I am looking for... Any direction on where to go?
This would be the output table for example:
**Table 2**
event1-- event2--
---A------B------
---B------C------
---C------D------
---A------C------
---C------E------
Thanks,
You can get the previous or next event using lag()
or lead()
:
select event,
lead(event) over (partition by palletnumber order by recorddate) as next_event
from datasample;
If you want to eliminate duplicates, I would be inclined to use group by
, because this also gives the ability to count the number of times that each pair appears:
select event, next_event, count(*) as cnt
from (select event,
lead(event) over (partition by palletnumber order by recorddate) as next_event
from datasample
) ds
group by event, next_event;