Skip to content
Advertisement

Fill in missing dates and grouping problem

I have a table with Case records with CaseId, UserId, Opened date, Closed date etc value.

For reporting I need to have a result table with all users by continuous months with number of case still opened with amount and number of closed case with amount.

Output desired (*values in parenthesis are only for helping)

I tried to play with CROSS JOIN, OVER (PARTITION) but I didn’t find the solution. Thanks for you help.

Advertisement

Answer

I would first cross join the available year/month and users available to generate the rows. Then, union all in a subquery can be used to unpivot the opening and closing information (one could possibly use cross apply too).

The final step is aggregation and window computation:

Demo on DB Fiddle:

userID | year_month | no_cases_still_open | value_open | no_closed | value_closed
:----- | :--------- | ------------------: | ---------: | --------: | -----------:
U1     | 2020-01-01 |                   3 |        770 |         0 |            0
U1     | 2020-02-01 |                   2 |        270 |         2 |          640
U1     | 2020-03-01 |                   3 |        690 |         0 |            0
U1     | 2020-04-01 |                   3 |        720 |         1 |          150
U1     | 2020-05-01 |                   2 |        300 |         1 |          420
U2     | 2020-01-01 |                   0 |          0 |         1 |          100
U2     | 2020-02-01 |                   1 |        790 |         0 |            0
U2     | 2020-03-01 |                   1 |        790 |         1 |          640
U2     | 2020-04-01 |                   2 |       1110 |         0 |            0
U2     | 2020-05-01 |                   1 |        790 |         1 |          320
U3     | 2020-01-01 |                   1 |        350 |         0 |            0
U3     | 2020-02-01 |                   1 |        350 |         0 |            0
U3     | 2020-03-01 |                   2 |       1160 |         0 |            0
U3     | 2020-04-01 |                   2 |       1160 |         0 |            0
U3     | 2020-05-01 |                   3 |       1390 |         0 |            0
U4     | 2020-01-01 |                   0 |          0 |         0 |            0
U4     | 2020-02-01 |                   2 |        680 |         0 |            0
U4     | 2020-03-01 |                   1 |        490 |         1 |          190
U4     | 2020-04-01 |                   2 |        700 |         0 |            0
U4     | 2020-05-01 |                   1 |        490 |         1 |          210
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement