Skip to content
Advertisement

Find rows using in between values in MySQL

I found it really hard to come up with a descriptive problem title, so I’ll give a bit of context.

We have a list of boats and a list of docks. Boats can be transferred from one dock to the other on a specific datetime, or it could be at no dock at all. I’m trying to find out which boats are at a specific dock at a given moment in time.

Here’s a simplified SQL to illustrate the data model

The expected output for dock 1 and date 2020-01-15 would be 1.

The expected output for dock 2 and date 2020-02-15 would be 1, 2.

I’ve tried a lot of things including fancy joins but cannot get it to work. Any help is greatly appreciated!

Advertisement

Answer

You can use a correlated subquery to determine which boat is where at a given point in time. The rest is just filtering:

You can also use window functions to assign a time period for each boat at each dock:

Here is a db<>fiddle.

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