I am running this script to generate a SQL Calender. I then want to join the calendar to my database and get a week by week count of Items Sold by week. My calendar generates no issue, but my Select statement is what is giving me fits. Can someone help remedy this?
--Script To Generate Calendar USE [TestDB] GO ALTER PROCEDURE [dbo].[CreateCalendar] AS BEGIN if OBJECT_ID ('dbo.Calendar') IS NOT NULL begin drop table dbo.Calendar end CREATE TABLE dbo.Calendar ( CalendarYear int NOT NULL, CalendarWeek int NOT NULL, WeekStartDate varchar(50), WeekEndDate varchar(50), constraint PK_Calendar PRIMARY KEY (CalendarYear, CalendarWeek) ) SET datefirst 6 DECLARE @StartDate datetime, @NumOfDays int SET @StartDate = '20130101' SET @NumOfDays = 720 ;WITH calendar AS ( SELECT TOP (@NumOfDays) dateadd(day, row_number() OVER (ORDER BY sc1.column_id)-1, @StartDate) AS CalendarDate FROM sys.columns sc1 cross join sys.columns sc2 ) INSERT INTO dbo.Calendar (CalendarYear, CalendarWeek, WeekStartDate, WeekEndDate) SELECT DATEPART(year, c.CalendarDate) AS Year, convert(varchar(100),DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week, MAX(CASE DATEPART(WEEKDAY, c.CalendarDate) WHEN 1 then convert(varchar(50),c.CalendarDate,101) else null end) As StartDate, MAX(CASE DATEPART(WEEKDAY, c.CalendarDate) WHEN 7 then convert(varchar(50),c.CalendarDate,101) else null end) As EndDate FROM calendar c GROUP BY DATEPART(year, c.CalendarDate), DATEPART(Week, c.CalendarDate) ORDER BY Year, startdate, convert(varchar(100),DATEPART(week, c.CalendarDate))--Week update dbo.Calendar set WeekStartDate = convert(VARCHAR(50), dateadd(day, 1, dateadd(week, -1, cast(WeekEndDate as datetime))), 101) where WeekStartdate is null update dbo.Calendar set WeekEndDate = convert(VARCHAR(50), dateadd(day, -1, dateadd(week, 1, WeekStartDate)), 101) where WeekEndDate is null SELECT * FROM dbo.Calendar END --Query trying to select a Count based off week production SELECT COUNT(a.ItemSold) As Sold, a.InternalSalesRep, cl.CalendarWeek FROM ProductionDatabase a INNER JOIN dbo.Calendar cl ON a.SaleDate >= cl.WeekStartDate AND a.SaleDate < cl.WeekEndDate GROUP BY cl.CalendarWeek, a.SaleDate, a.InternalSalesRep ORDER BY cl.CalendarWeek ASC