2013-09-10 64 views
0

我想根据一个时间段及其以下时间段的出现次数来显示条件的计数。SQL连续出现次数

比方说,这是表格的布局

Key1  | Key2    | Key3   | emailSent_Date | 
08/01/2013| 0097A    | 0097A   | 07/01/2013  | 
07/01/2013| 0097A    | 0097A   | 08/01/2013  | 
06/01/2013| 0097A    | 0097A   | 08/01/2013  | 

所需的输出:SQL查询来获取KEY2和KEY3出现的计数的时间段和它下面timperiods。计数必须是连续的。

这里,对于8月份的key2和key3发生了3次。但是,在七月份,key2和key3只发生了两次。对不起,如果我把它变得复杂。

Key1  | Key2    | Key3   | emailSent_Date | Count | 
08/01/2013| 0097A    | 0097A   | 07/01/2013  | 3  | 
07/01/2013| 0097A    | 0097A   | 08/01/2013  | 2  | 
06/01/2013| 0097A    | 0097A   | 08/01/2013  | 1  | 

回答

0

我觉得这正是row_number()做:

select key1, key2, key3, emailSent_Date, 
     row_number() over (partition by key2, key3 order by key1) as "Count" 
from "table";