0

I have a table with these rows:

City     | Day
NEWYORK  | MON
NEWYORK  | MON
NEWYORK  | MON
NEWYORK  | TUE
CHICAGO  | MON
CHICAGO  | MON

I need to write a query to add column Occurrence to the result using data from Columns City and Day:

City     | Day    | Occurrence
NEWYORK  | MON    |   1
NEWYORK  | MON    |   2
NEWYORK  | MON    |   3
NEWYORK  | TUE    |   1
CHICAGO  | MON    |   1
CHICAGO  | MON    |   2  

EG: For NEWYORK if MON occurs 1st then Occurrence=1, if MON occurs twice then corresponding Occurrence=2 and so on.

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

2

The row_number window function should do exactly what you're looking for:

SELECT [city], [day], ROW_NUMBER() OVER (PARTITION BY [city], [day] ORDER BY 1) AS [occurence]
FROM   my_table;
Dan Guzman
  • 43,250
  • 3
  • 46
  • 71
Mureinik
  • 297,002
  • 52
  • 306
  • 350