Skip to content
Advertisement

SQL Query to Count Daily Totals Skips Days

This query counts the amount of bottles we produce over a month and groups them by day. If there are no bottles produces that day then it is skipped from the output instead of returning 0 bottles produced. How can I return with the day’s timestamp if there are no bottles produced? I heard the calendar table has to be used for this.

Current Output:

Desired Output:

Advertisement

Answer

You need to generate the days. A pretty simple method uses a recursive CTE:

Notes:

  • If you have a calendar or tally table, then use that instead.
  • If the number of dates exceed 100, you need to add OPTION (MAXRECURSION 0).
  • COUNT(bottles) looks suspicious. Do you really intend SUM(bottles)?
  • Converting a column to a date and then to a datetime is also suspicious. It is unclear why you would want a datetime for the first column.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement