Hi Statalist colleagues,

I have a question regarding max().

So I am trying to extract max and second to max values of a series, but having hard time for the latter one.

For the max,
What I did was

Code:
by id year: egen top1= max(x)
But I could not figure out how I should create a variable for top2, i.e. second to max value.

Thanks much,
Jinny

P.S. My dataset looks as follows:

Code:
id     year     x    top1
102634    2006    1    3
102634    2006    3    3
102634    2006    3    3
102634    2006    3    3
102634    2007    1    3
102634    2007    3    3
102634    2007    3    3
102634    2007    3    3
102634    2008    1    2
102634    2008    2    2
102634    2008    2    2
102634    2009    1    3
102634    2009    3    3
102634    2009    3    3
102634    2009    3    3
102634    2010    1    3
102634    2010    3    3
102634    2010    3    3
102634    2010    3    3
102634    2011    1    3
102634    2011    3    3
102634    2011    3    3
102634    2011    3    3
102634    2012    1    3
102634    2012    3    3
102634    2012    3    3
102634    2012    3    3
102634    2013    1    3
102634    2013    3    3
102634    2013    3    3
102634    2013    3    3
102634    2014    1    3
102634    2014    3    3
102634    2014    3    3
102634    2014    3    3
102634    2015    1    3
102634    2015    3    3
102634    2015    3    3
102634    2015    3    3
102634    2016    1    1
102634    2016    1    1
102634    2017    1    1
102634    2017    1    1
102634    2018    1    1
102634    2018    1    1
102634    2019    1    1
102634    2019    1    1
1122135    2006    1    1
1122135    2007    1    1
1122135    2008    1    1
1122135    2009    1    1
1122135    2010    1    1
1122135    2011    1    1
1122135    2012    1    1
1122135    2013    1    1
1122135    2014    1    1
1132032    2017    1    1
1132032    2018    1    1
1132032    2019    1    1
1152035    2017    1    1
1152035    2018    1    1
1152035    2019    1    1
2112135    2015    1    1
2112135    2016    1    1
2112135    2017    1    1
2112135    2018    1    1
2112135    2018    1    1
2112135    2019    1    1
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2006    9    9
5152235    2007    8    8
5152235    2007    8    8
5152235    2007    8    8
5152235    2007    8    8
5152235    2007    8    8
5152235    2007    8    8
5152235    2007    8    8
5152235    2007    8    8
5152235    2008    5    5
5152235    2008    5    5
5152235    2008    5    5
5152235    2008    5    5
5152235    2008    5    5
5152235    2009    7    7
5152235    2009    7    7
5152235    2009    7    7