Creation Date Account Number FREQUENCY - 7
2/3/15 3:47 PM 7522461 0
2/4/15 9:25 AM 7522461 1
2/4/15 4:34 PM 7522461 2
2/23/15 3:08 PM 7522461 0
3/4/15 9:58 AM 7522461 0
3/4/15 4:55 PM 7522461 1
3/5/15 2:27 PM 7522461 2
3/6/15 7:28 AM 7522461 3
3/6/15 1:33 PM 7522461 4
3/9/15 8:51 AM 7522461 5
我需要了解如何计算在7天时间戳内重复的帐号#的频率。例如:2/3/15 3:47 PM
到2/4/15 4:34 PM
属于7天内,因此第一次出现0
,同一7天内第二次出现1
,第三次出现在同一7次内天将2
等等。
答案 0 :(得分:1)
使用用户定义的变量来跟踪1周间隔的开始和一周内的计数器。当创建日期超过1周后,重置变量。
SELECT CreationDate, AccountNumber,
@frequency := IF(CreationDate > DATE_ADD(@startdate, INTERVAL 7 DAY), 0, @frequency + 1) AS Frequency,
@startdate := IF(CreationDate > DATE_ADD(@startdate, INTERVAL 7 DAY), CreationDate, @startDate)
FROM (SELECT CreationDate, AccountNumber
FROM YourTable
ORDER BY CreationDate) AS x
CROSS JOIN (SELECT @startdate := DATE('1900-01-01'), @frequency := 0) AS vars
答案 1 :(得分:0)
如果是MSSQL,请试试这个
SELECT CreationDate, AccountNumber,
(SELECT COUNT(*)
FROM YourTable t2
WHERE (DATEDIFF(day, t2.CreationDate, t1.CreationDate ) < 7 AND
(DATEDIFF(day, t2.CreationDate, t1.CreationDate) > 0 OR
(DATEDIFF(day, t2.CreationDate, t1.CreationDate) = 0
AND DATEDIFF(second, t2.CreationDate, t1.CreationDate) > 0
)
)
)
AND t2.AccountNumber = t1.AccountNumber)
FROM YourTable t1
order by AccountNumber, CreationDate