Skip to content
Advertisement

Oracle SQL: check amount of active users on given date (check closest date of grouped field)

Have a table given, holding the status history of a user:

ID USERID MODIFIED STATUS
1 1 01.01.2020 inactive
2 1 01.07.2020 active
3 2 04.08.2020 active
4 2 04.06.2020 active
5 2 01.08.2020 inactive
6 2 01.10.2020 active
7 3 01.09.2020 inactive

I want to provide a date, i.e. 01.07.2020, and understand how many UserIds were active on that day.

I therefor need to check the modified date which is closest but not above 01.07.2020, grouped by the userid.

Desired result for 01.07.2020:

ID USERID MODIFIED STATUS
2 1 01.07.2020 active
4 2 04.06.2020 active

From there I could just sum the status, and see I had two users active on the checked date of 01.07.2020.

Current approach for first step:

it does not yet provide fully correct results

the final step would then be a simple sum I assume, something like:

Advertisement

Answer

You can use row_number() to get the last status as of that date:

Another option is a correlated subquery:

Or, you can use two levels of aggregation:

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