• Thanks for the suggestions guys. I am sorry i should not have used "P1" & "p2" as codes, these are just my examples codes actual values won't have any correlation with Id (e.g. actual code value could be "2956" or "4684" etc) so i cannot use what you guys suggested.

    I want a solution that doesn't depend on values. I was thinking something like, get minimum code for the first matching record, then get the minimum code (greater than the code applied on first record) for the second record and so on.