This is a crazy question but basically we need to mark the first row that matches a condition but not the rest, for example we have a history of all users daily Logins but each month we want to show the login that was before a specific date, for example:
UserId LoginDate
1 2011-12-31
2 2012-12-31
1 2012-01-01
2 2012-01-02
1 2012-01-02
2 2012-01-03
etc….
We want a SQL Query that will return the login that is first for each month in a result set similar to:
UserId LoginDate WasFirstLoginOfMonth
1 2011-12-31 0
2 2012-12-31 0
1 2012-01-01 1
2 2012-01-02 1
1 2012-01-02 0
2 2012-01-03 0
etc….
I know this seems like a crazy requirement but we need to know which login satisfied a certain date condition but only one can and the rest can’t.
Is there any way to do this without a slow sub-select for each row to see if it was the first?
Many thanks for any help.
The
row_number()function allows you to partition and sort data.So in this query, rn represents the ordinal of the login, by user, year and month, so when that value is
1, that is the first login of the month.