Post by BenWHi,
OrderDate (DateTime) Quantity (Int)
02/03/2012 100
02/03/2012 65
02/02/2012 90
02/01/2012 110
01/30/2012 130
01/29/2012 140
01/27/2012 150
01/26/2012 160
.....
I want to create a weekly report to show sum(Quantity) by week. But
the week here is not a nature week in SQL server. The week means that
from 7 days ago to today.
I know that I can use WHILE in a cursor to do this.
Is there any simple solution for this?
Hopefully you are using SQL 2005 or higher. This does the trick. Give it a
study and let us know if there's anything about it you don't understand. It
uses a recursive common table expression (CTE) to generate a table of
numbers from 0 to 52 (53 weeks - change the "52" to a higher or lower number
in both locations as needed) which are used to calculate week start and end
dates so the data can be grouped by those dates. To use it in your database,
delete the first CTE (everything from "Data" to "Nbrs", leaving the word
"Nbrs", but deleting the comma before the word so the statement begins "WITH
Nbrs (n) ... " and replace "Data" in the FROM clause with the name of your
table.
WITH Data (OrderDate,Quantity) AS (
select CAST('20120203' AS DATETIME),100
union all select CAST('20120203' AS DATETIME),65
union all select CAST('20120202' AS DATETIME),90
union all select CAST('20120201' AS DATETIME),110
union all select CAST('20120130' AS DATETIME),130
union all select CAST('20120129' AS DATETIME),140
union all select CAST('20120127' AS DATETIME),150
union all select CAST('20120126' AS DATETIME),160)
,Nbrs ( n ) AS (
SELECT 0 UNION ALL
SELECT 1 + n FROM Nbrs WHERE n < 52 )
, Weeks (WeekStartDate, WeekEndDate) AS (
SELECT
DATEADD(d,1,DATEADD(ww,-1*(n+1),DATEADD(d,DATEDIFF(d,0,CURRENT_TIMESTAMP),0)
))
,DATEADD(d
,1,DATEADD(ww,-1*n,DATEADD(d,DATEDIFF(d,0,CURRENT_TIMESTAMP),0)))
FROM Nbrs
)
SELECT WeekStartDate,SUM(Quantity) AS WeeklyTotal FROM Weeks AS w JOIN
Data AS d ON OrderDate >=WeekStartDate
AND OrderDate < WeekEndDate
GROUP BY WeekStartDate
ORDER BY WeekStartDate
OPTION (MAXRECURSION 52)