Reputation: 23
I have an event record database, I need to find all events for each costumer and group them in one week interval from the last record of each costumer until the first.
FirstEvent LastEvent Client
==
2011-01-01 06:55:21.000 |2011-04-30 21:46:09.000 |Client1
2011-01-01 06:20:00.000 |2011-02-23 12:43:55.000 |Client2
2011-01-03 08:34:33.000 |2011-04-30 09:00:39.000 |Client3
2011-01-01 02:14:45.000 |2011-04-30 15:31:41.000 |Client4
2011-01-01 08:08:12.000 |2011-02-21 09:41:28.000 |Client5
2011-02-01 11:29:28.000 |2011-04-29 09:13:25.000 |Client6
Now I have to count the records of each client and group them like this
Client From To Records
==
Client1 |2011-04-30 21:46:09.000 |2011-04-23 21:46:09.000 |200
Client1 |2011-04-16 21:46:09.000 |2011-04-09 21:46:09.000 |400
...Until the the first date
Client1 |2011-01-08 06:55:21.000 |2011-01-01 06:55:21.000 |250
Client2 |2011-02-23 12:43:55.000 |2011-02-16 12:43:55.000 |50
...The same for each user
I hope someone can help me find a way to output this.
Upvotes: 2
Views: 2502
Reputation: 2364
This should work if the number of weeks between the start and end is less than 2048, if not then I would suggest using a numbers table.
SELECT
client
,DATEADD(WK,(number * -1) -1,fromdate) as [from]
,DATEADD(WK,number * -1,fromdate) as [to]
,COUNT(client) as records
from #sample
LEFT OUTER JOIN (SELECT number FROM dbo.spt_values WHERE type = 'p') nums
on nums.number <= DATEDIFF(WK,todate,fromdate)
GROUP BY client
,DATEADD(WK,(number * -1) -1,fromdate)
,DATEADD(WK,number * -1,fromdate)
ORDER BY
client
,DATEADD(WK,(number * -1) -1,fromdate) DESC
Upvotes: 0
Reputation: 77935
Okay, I think this does exactly what you wish for:
SELECT CONVERT(datetime, '2011-01-01 06:55:21.000', 120) AS event, 'client1' AS Client
INTO #EVENTS
UNION ALL SELECT '2011-01-08 06:55:20.000', 'client1'
UNION ALL SELECT '2011-04-30 21:46:09.000', 'client1'
;WITH E AS (
SELECT
Client,
MIN(event) AS FirstEvent
FROM #EVENTS
GROUP BY Client
)
,B AS (
SELECT
E.Client,
E.FirstEvent,
COUNT(*) AS Records,
DATEDIFF(DAY, 0, c.event - E.FirstEvent) / 7 AS [weeks]
FROM #EVENTS c
JOIN E ON E.Client = c.Client
GROUP BY E.Client, E.FirstEvent, DATEDIFF(DAY, 0, c.event - E.FirstEvent) / 7
)
SELECT
Client,
DATEADD(WEEK, weeks, FirstEvent) AS [From],
DATEADD(WEEK, weeks + 1, FirstEvent) AS [To],
Records
FROM B
ORDER BY Client, weeks;
DROP TABLE #EVENTS
Though, if there are no records a certain week, it will leave out that row instead of returning a row containing the Records value of 0:
Edit:
If you wonder why I use DAY
instead of WEEK
for my DATEDIFF
, it is to avoid problems whether Sunday or Monday is the first day of the week.
Upvotes: 1
Reputation: 17957
You can group by week using the DATEDIFF function.
SELECT e.[Client]
, [From] = MIN(e.EventDate)
, [To] = MAX(e.EventDate)
, [Records] = COUNT(*)
FROM Events AS e
GROUP BY e.[Client]
, DATEDIFF(week, '1900-01-01', e.EventDate)
Upvotes: 2