Skip to content
Advertisement

SQL Server : getting sum of values in “calendar” table without joining

Is it possible to get a the sum of value from the calendar_table to the main_table without joining like below?

I am trying to avoid a join like this because main_table is a very large table with rows that have very large start and end dates, and it is absolutely killing my performance. And I’ve already indexed both tables.

Sample desired results:

Sample tables

calendar_table:

main_table:

Advertisement

Answer

You want the sum in the calendar table. So, I would recommend an “incremental” approach. This starts by unpivoting the data and putting the value as an increment and decrement in the results:

The final step is to aggregate and do a cumulative sum:

This is processing two rows of data for each row in the master table. Assuming that your time spans are longer than two days typically for each master row, the resulting data processed should be much smaller. And smaller data implies a faster query.

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