Example: I need Sum of Submissions week wise for zone2 from 06/01/2010 to 06/24/2010.
This T-SQL should do it:
(I kept the date cast in one spot because 'yyyy-mm-dd' is not a language-independent date format.)
DECLARE
@StartDate DATETIME,
@EndDate DATETIME,
@TargetZone INT
SET @StartDate = '2010-06-01'
SET @EndDate = '2010-06-24'
SET @TargetZone = 2
SELECT
SUM (dwd.TotalSubmissions) AS TotalSubmissions,
dwd.ZoneID,
DATEPART (week, dwd.ReportDate) AS WeekOfTheYear
FROM
(
SELECT
r.TotalSubmissions,
r.ZoneID,
CAST ( (CAST (r.RptYear AS varchar(4)) + '-' + CAST (r.RptMonth AS varchar(2)) + '-' + CAST (r.RptDay AS varchar(2))) AS DATETIME) AS ReportDate
FROM
Reports r
WHERE
r.ZoneID = @TargetZone
)
AS dwd
WHERE
dwd.ReportDate >= @StartDate
AND
dwd.ReportDate <= @EndDate
GROUP BY
dwd.ZoneID,
DATEPART (year, dwd.ReportDate),
DATEPART (week, dwd.ReportDate)
Sample Data:
CREATE TABLE Reports
(
TotalSubmissions INT,
ZoneID INT,
RptMonth INT,
RptDay INT,
RptYear INT
)
INSERT INTO
Reports (TotalSubmissions, ZoneID, RptMonth, RptDay, RptYear)
SELECT
2, 1, 6, 1, 2010 UNION ALL SELECT
1, 1, 6, 2, 2010 UNION ALL SELECT
1, 1, 6, 3, 2010 UNION ALL SELECT
1, 2, 6, 1, 2010 UNION ALL SELECT
1, 2, 6, 2, 2010 UNION ALL SELECT
2, 2, 6, 3, 2010 UNION ALL SELECT
1, 2, 6, 4, 2010 UNION ALL SELECT
1, 4, 6, 1, 2010 UNION ALL SELECT
1, 4, 6, 3, 2010 UNION ALL SELECT
1, 4, 6, 4, 2010
INSERT INTO Reports (TotalSubmissions, ZoneID, RptMonth, RptDay, RptYear)
SELECT TotalSubmissions, ZoneID, RptMonth, RptDay+10, RptYear
FROM Reports
INSERT INTO Reports (TotalSubmissions, ZoneID, RptMonth, RptDay, RptYear)
SELECT TotalSubmissions, ZoneID, RptMonth, RptDay+20, RptYear
FROM Reports
DELETE FROM Reports
WHERE RptDay > 30