Monday, February 16, 2015

How to find the Second value (could be largest or lowest) from a table.?


I have One table with StatusIDHeld in "UserStatusHistory"Table with this column userid,StatusIDHeld and statusChangedOn. One customer could be multiple StatusIDHeld . I am finding out just previous one StatusIDHeld that mean the second StatusIDHeld which just before he had hold.

To be able to get 1., 2. or n-th record depending on sort order, use ROW_NUMBER() function.
                        SELECT StatusIDHeld 
   FROM
   (
    SELECT StatusIDHeld, ROW_NUMBER () OVER(order by statusChangedOn DESC) as RowNo
    FROM UserStatusHistory where userid= 1037146 
   ) AS t
   where t.RowNo = 2


Happy Query .....

1 comment:

  1. Thanks for your post... its a helpful for me ..

    ReplyDelete