Skip to content
Advertisement

Returning Records by Week

I’m trying to come up with a way to return a result set from the below data without a loop that shows the number of records by Team for a particular date range by week.

I’ve got a Date table (https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/) that has every day/week/year referenced, but not sure how to connect it up.

I’ve got this query:

Where it fails is:

  1. It doesn’t include the teams with 0 results
  2. I need to be able to show results for multiple weeks through a date range. In the above example, they would be 0.

Advertisement

Answer

I think the trick is to first generate all the rows you need, then LEFT JOIN those onto their results to get what you want.

Note that in your query, you are pulling out WeekOfYear and WeekOfMonth, but you probably also want to pull out Year in case the data crosses years or goes for multiple years.

For the date range

  • I have two variables @RangeStart and @RangeEnd– both dates – to do filtering
  • I create a table (probably incorrect) to model the date dimension table

Results for the above, with your data and my date table and range dates applied (noting that the date range I selected gets the first value in #Entries for 2 Nov, but doesn’t get the second for 4 Nov).

Note that in this case I am creating all possible dates, then grouping to get week-by-week at the very end. It is possible to also do this by grouping into week-by-week data as soon as possible (e.g., the CTE will return data by week instead of day, then the outer part of the LEFT JOIN also then needs to be grouped into weeks first).

This gives the same results, and possibly provides a performance benefit, but is more complex and you’d probably need to ensure that SQL Server is getting accurate estimates/etc when doing the multiple GROUP BYs.

As such I wouldn’t use it unless there is a performance issue with the first one – and if there was, I’d also try turning the CTE into a temporary table first, then joining that to #Entries.

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