简体   繁体   中英

SQL consecutive occurrences count

I want to display the count of a criteria based on its occurrence for a time period and its below time periods.

Let's say this is the table layout

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     | 

Desired output : SQL query to get the count of key2 and key3 occurrences for a time period and its below timperiods. The count has to be consecutive.

Here, for august month key2 and key3 occurred for 3 times. But, for the july month, key2 and key3 occurred for two times only. Sorry if I made it complex.

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     | 

I think this is exactly what row_number() does:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM