Skip to content
Advertisement

Getting the latest status of user before every calendar Date in SQL

I have 2 tables as below:

Table 1:

Table 2 : A simple calendar table

Required output: For every date I want to return the latest status on or before it for every userID.

Similarly for other calendar dates and other userIds.

Anyone has a clue how to do it? Thanks in advance!

Advertisement

Answer

For every date I want to return the latest status on or before it for every userID.

In standard SQL, you can generate the rows using cross join and then use a join. The key idea is to use lead() for the join:

In SQL Server, you can also express this using outer apply:

Here is a db<>fiddle.

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