I would like to create an integer counter for duplicate entries on an intermediate table in an import step. Let’s say I have a table called FinalTable, which looks like this:
FinalTable
ID Date SameDateCounter
1003 2012/01/01 NULL
1004 2012/02/01 NULL
1005 2012/03/01 1
1006 2012/03/01 2
1007 2012/03/01 3
1008 2012/04/01 1
1009 2012/04/01 2
And has a unique constraint on (Date, SameDateCounter). In the intermediate step the data is in IntermediateTable, which looks exactly like FinalTable except that it doesn’t have any constraints. So the starting point for this problem is here:.
IntermediateTable:
ID Date SameDateCounter
1003 2012/01/01 NULL
1004 2012/02/01 NULL
1005 2012/03/01 NULL
1006 2012/03/01 NULL
1007 2012/03/01 NULL
1008 2012/04/01 NULL
1009 2012/04/01 NULL
And I need to generate the values for SameDateCounter, starting at one, where the date appears more than once.
You can use the
ROW_NUMBER()function combined with aPARTITION BYclause:The
PARTITION BY Dateclause groups every separate value ofDateinto its own “partition”, andROW_NUMBER()hands out numbers starting at 1, for each partition.So your
SameDayCounterwill start at 1 for each new day and will show the rows for that particular day.