Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Calculating Total number of visits

Author  Topic 

DeJesus
Starting Member

2 Posts

Posted - 2011-02-05 : 23:12:38
Hi All,

I need help calculating the number of visits in the last 12 months, here's an example:

CustomerID MonthID MonthDate NumOfVisits
001 200405 2004-05-01 1
001 200406 2004-06-01 2
001 200407 2004-07-01 1
001 200505 2005-05-01 5
001 200507 2005-07-01 10
002 200811 2008-11-01 3
002 200811 2008-11-20 1

The result should look like
CustomerID MonthID NumOfVisitsInLast12Month
001 200405 1
001 200406 3
001 200407 4
001 200505 10
001 200507 16
002 200811 4

It looks like running total, isn't it? I am using SQL Server 2008

Thank you!

malpashaa
Constraint Violating Yak Guru

264 Posts

Posted - 2011-02-06 : 02:26:00
Try something like this:

DECLARE @NumOfVisits TABLE
(
CustomerID INT NOT NULL,
MonthID INT NOT NULL,
MonthDate DATE NOT NULL,
NumOfVisits INT NOT NULL,
PRIMARY KEY(CustomerID, MonthDate)
);

INSERT INTO @NumOfVisits(CustomerID, MonthID, MonthDate, NumOfVisits)
VALUES(001, 200405, '20040501', 1),
(001, 200406, '20040601', 2),
(001, 200407, '20040701', 1),
(001, 200505, '20050501', 5),
(001, 200507, '20050701', 10),
(002, 200811, '20081101', 3),
(002, 200811, '20081120', 1);

SELECT T1.CustomerID, T1.MonthID, T2.NumOfVisitsInLast12Month
FROM (SELECT T1.CustomerID, T1.MonthID,
DATEADD(DAY, -1, DATEADD(MONTH, 1, CAST(CAST(T1.MonthID AS CHAR(6)) + '01' AS DATE))) AS MonthDate
FROM @NumOfVisits AS T1
GROUP BY T1.CustomerID, T1.MonthID) AS T1
CROSS APPLY
(SELECT SUM(T2.NumOfVisits) AS NumOfVisitsInLast12Month
FROM @NumOfVisits AS T2
WHERE T2.CustomerID = T1.CustomerID
AND T2.MonthDate <= T1.MonthDate
AND T2.MonthDate > DATEADD(MONTH, -13, T1.MonthDate)) AS T2;
Go to Top of Page

DeJesus
Starting Member

2 Posts

Posted - 2011-02-06 : 03:16:52
Thank you!!
Go to Top of Page

malpashaa
Constraint Violating Yak Guru

264 Posts

Posted - 2011-02-06 : 05:43:50
Welcome
Go to Top of Page
   

- Advertisement -