在上一个问题(请参阅:SQL Keeping count of occurrences)中,我需要计算一个变量的出现次数。
提供的代码如下:
SELECT
[Date], Code,
[Count] = COUNT(*) OVER (PARTITION BY Code ORDER BY [Date] ROWS UNBOUNDED PRECEDING)
FROM dbo.YourTable
ORDER BY [Date];
但是,现在我需要对该代码进行改进:
假设我有下表:
Date | Code
------------------------
2010/01/01 | 25
2010/01/01 | 22
2010/01/01 | 23
2010/01/01 | 25
2010/01/02 | 23
2010/01/02 | 23
2010/01/03 | 23
2010/01/04 | 23
2010/01/05 | 23
2010/01/06 | 23
2010/01/07 | 23
.....
2013/03/02 | 21
现在,我需要计算特定时间段内出现的次数。所需的输出如下(为简单起见,假设时间范围为 n=2 天)
Date | Code | Occurrences
------------------------------------
2010/01/01 | 25 | 1
2010/01/01 | 22 | 1
2010/01/01 | 23 | 1
2010/01/01 | 25 | 2
2010/01/02 | 23 | 2
2010/01/02 | 23 | 3
2010/01/03 | 23 | 3 -> We are not considering the occurence in 2011/01/01 as it is out of the scope now
2010/01/04 | 23 | 2 -> Considers only occurrences in 01/03 and 01/04
2010/01/05 | 23 | 2
2010/01/06 | 23 | 2
2010/01/07 | 23 | 2
.....
2013/03/02 | 21 | 1
也就是说,我需要知道代码“x”在过去“n”个月内出现在我的表中的次数。
这是在 SQL Server 2012 中运行的。
先感谢您。