I want to fetch count of items for a week from a table and I used the below query:
SELECT
count(*) As Total
from MyTable
WHERE convert(date,DateCreated)>='08/17/2015'
AND convert(date,DateCreated)<='08/23/2015'
I get the result as (which is correct):
Total
1149
Now I tried to rewrite the query to make it return the result on a weekly basis over a period of time and I noticed the count is not showing correctly. As a sample, I used the below query for same time period:
SELECT
count(*) AS Total,
DATEPART(wk, DateCreated) AS WeekNumber,
CAST(dateadd(ww, datediff(ww, 0, DateCreated), 0) AS date) as WeekStartDate,
CAST(dateadd(ww, datediff(ww, 0, DateCreated), 6) AS date) as WeekEndDate
FROM MyTable
WHERE convert(date,DateCreated) >= '08/17/2015'
and convert(date,DateCreated) <= '08/23/2015'
GROUP BY DATEPART(wk, DateCreated), CAST(dateadd(ww, datediff(ww, 0, DateCreated), 0) AS date), CAST(dateadd(ww, datediff(ww, 0, DateCreated), 6) AS date)
ORDER BY DATEPART(wk, DateCreated)
The SUM
of rows is returning the correct count, but it is expected to come as a single row only since my date selection (from '08/17/2015'
to '08/23/2015'
) represents a week only, but the result as below shows as 2 weeks
Total WeekNumber WeekStartDate WeekEndDate
1078 34 2015-08-17 2015-08-23
71 35 2015-08-24 2015-08-30
Any known reason for this behaviour. Is it because of week calculation logic I am using? Or some other known issues.