I have a query to fetch the count on a daily basis where the startdate and enddate are parameters passed from the application and I used a sample dates here to demonstrate the query
SELECT
CAST(DateCreated AS DATE) AS Date,
COUNT(0) AS Total
FROM
SessionTable
WHERE
DateCreated >= '10/02/2015'
AND CONVERT(DATE, DateCreated) <= '10/30/2015'
GROUP BY
CAST(DateCreated AS DATE)
ORDER BY
CAST(DateCreated AS DATE)
This will return the result in format
Date Total
Now I decided to reduce the number of records by converting date-wise count to week-wise count and I use the query
SELECT
DATEPART(wk, DateCreated) AS WeekNumber,
COUNT(0) AS WeekCount
FROM
SessionTable
WHERE
DateCreated >= '10/02/2015'
AND CONVERT(DATE, DateCreated) <= '10/30/2015'
GROUP BY
DATEPART(wk, DateCreated)
This returns the result in the format and is working fine
WeekNumber WeekCount
-------------------------
40 2298
41 13998
42 19454
43 19923
To make the result set more clear i am planning to add the begin date and end date of each week as well to the above result set , but struggled to do so
My expected result is
WeekNumber BeginDate EndDate WeekCount
To fetch the weekBegin and End Date How do you get the "week start date" and "week end date" from week number in SQL Server? suggestion from this can be used and i written the query like
SELECT
DATEPART(wk, DateCreated) AS WeekNumber,
DATEADD(dd, -(DATEPART(dw, DateCreated)-1), DateCreated) as [WeekStart],
DATEADD(dd, 7-(DATEPART(dw, DateCreated)), DateCreated) as [WeekEnd],
COUNT(0) AS WeekCount
FROM
Session
WHERE
DateCreated >= '10/02/2015'
AND CONVERT(DATE, DateCreated) <= '10/30/2015'
GROUP BY
DATEPART(wk, DateCreated),
DATEADD(dd, -(DATEPART(dw, DateCreated)-1), DateCreated),
DATEADD(dd, 7-(DATEPART(dw, DateCreated)), DateCreated)
But this returned my resultset with a count as 1 for each day something like below
WeekNumber WeekStart WeekEnd WeekCount
44 2015-10-25 18:02:26.527 2015-10-31 18:02:26.527 1
44 2015-10-25 10:53:16.057 2015-10-31 10:53:16.057 1
42 2015-10-11 11:23:57.253 2015-10-17 11:23:57.253 1
40 2015-09-27 09:04:39.063 2015-10-03 09:04:39.063 1
44 2015-10-25 10:44:38.573 2015-10-31 10:44:38.573 1
44 2015-10-25 14:33:31.803 2015-10-31 14:33:31.803 1
44 2015-10-25 08:18:28.020 2015-10-31 08:18:28.020 1
44 2015-10-25 12:19:21.270 2015-10-31 12:19:21.270 1
So how can I add BeginDate
and EndDate
values to each row from query correctly?