I have the following table ordered by Id, Year DESC
Id Year Valid 1 2011 1 1 2010 1 1 2009 0 1 2002 1 4 2013 1 4 2012 1 4 2011 1 etc.
What I would like to have is an extra rank field like:
Id Year Valid Rank 1 2011 1 1 1 2010 1 1 1 2009 0 2 1 2002 1 3 4 2013 1 1 4 2012 1 1 4 2011 1 1 etc.
Basically per Id alternating ranks for every change in the Valid field. In such a way I can query on the rank=1 field to have all Valid=1 records for each and every Id up to the first Valid=0. Or is there an easier way to select the first top number of records matching a certain condition (For Id=1 only the first two records). I already played with ROW_NUMBER(), RANK() and PARTITION BY but I can't seem to get it to work. Must avoid nesting of queries since the actual query is run against a large database.
Anyone any ideas?
Thanks and cheers, Nyquist