Skip to content
Advertisement

Grouping SQL rows based on overlapping active time intervals, valid from and valid to

I’m working in bigquery with this mock data:

and what I want to get out is the active lineups. The output would look like so:

https://imgur.com/a/2j8HPiD (upper image)

With the logic behind it being: ![enter image description here

I’ve almost cracked it using some sort of lead(valid_from) between valid_to and valid_from and, doing a case when to make it 1 if its a new lineup 0 otherwise, and then doing some sort of cumulative sum on that to get the ID but I’m not able to solve it 100%… I’m very desperate, don’t know where to look anymore.

**correction: lineup 4 & 5 should actually just be one lineup.

Advertisement

Answer

Given that a player can belong to multiple line up as we discussed in the comment section, you might try the approach below using JOIN:

enter image description here

Since the output is too long for me to show you via screenshot in Bigquery console, I extracted the results to Google sheets. See below screenshot of output:

enter image description here

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