I have an event table with lane1 and lane2 mapping colors as below.
event | lane1 | lane2 |
---|---|---|
79 | red | yellow |
83 | red | white |
87 | blue | red |
91 | yellow | white |
96 | green | white |
100 | navy | yellow |
103 | yellow | green |
107 | yellow | blue |
111 | yellow | navy |
115 | blue | navy |
119 | yellow | grey |
123 | white | grey |
Required Output:
Capture the nth entry of the color that appears in lane1 for the first time.
For the above input the required output is
event | lane1 | nth_entry |
---|---|---|
79 | red | 1 |
87 | blue | 1 |
91 | yellow | 2 |
96 | green | 1 |
100 | navy | 1 |
123 | white | 4 |
I tried aggregation query, like lane1, min(event) but not getting the required output.
select lane1, min(event) from colors group by lane1
4
Answers
You can perform a self-
join
on the first occurrences oflane1
values:See fiddle.
You could try:
One further option while exploiting window functions is:
Check the demo here.
We unpivot
lane2
usingunion all
and then userow_number()
to give us the first time a color appears inlane1
and how many time it appeared inlane2
previously.Fiddle