Hi,
Could anyone help to provide some ideas for the following query, I've been stucked for couple days already.
I got the following sample table:
RecordID | ProductID | Date | 30_First Rank | 30_Last Rank | 90_First Rank | 90_Last Rank |
1 | 1 | 05/08/2013 | NULL | NULL | NULL | NULL |
2 | 1 | 29/08/2013 | NULL | NULL | NULL | NULL |
3 | 2 | 10/05/2013 | NULL | NULL | NULL | NULL |
4 | 2 | 10/07/2013 | NULL | NULL | NULL | NULL |
5 | 2 | 02/08/2013 | NULL | NULL | NULL | NULL |
I would need to write a query or store procedure to rank/Row_Number the above records based on the product ID and order by days for each record: I would need to rank base on both 30 days window and 90 days window.
Here’s the define for the last 4 fields:
30_First Rank:
When same productID, compare of the previous record, if it's within 30 days, Rank/Row_Number the record, partition by Product ID, order by Date ASC.
For example, there are 24 days diffrent between record 2 and record 1(Same productID), therfore record 1 would be rank as 1 and record 2 will be rank as 2.
Similarly, there are 60 days different between record 4 and record 3, threrfore they both will be rank as 1. Record 5 will be rank as 2 as it's within 30 days comapre with record 4.
30_Last Rank:
When same productID, Compare of the previous record, if it's within 30 days, Rank/Row_Number the record, partition by Product ID, order by Date DESC.
90_First Rank:
When same productID, Compare of the previous record, if it's within 90 days, Rank/Row_Number the record, partition by Product ID, order by Date ASC.
90_Last Rank:
When same productID, Compare of the previous record, if it's within 90 days, Rank/Row_Number the record, partition by Product ID, order by Date DESC.
The table suppose to be refresh like below after executing the query/sp
RecordID | ProductID | Date | 30_First Rank | 30_Last Rank | 90_First Rank | 90_Last Rank |
1 | 1 | 05/08/2013 | 1 | 2 | 1 | 2 |
2 | 1 | 29/08/2013 | 2 | 1 | 2 | 1 |
3 | 2 | 10/05/2013 | 1 | 1 | 1 | 3 |
4 | 2 | 10/07/2013 | 1 | 2 | 2 | 2 |
5 | 2 | 02/08/2013 | 2 | 1 | 3 | 1 |
Any comments/links/codes will be helpful, many thanks!
Regards
Stephen