SQL Server – Get Max Serial Number by Sum of Corresponding Amount

sql serversql-server-2008sql-server-2012

I have a table with data as follows:

s_no  amount
1      500
2      500
3      500
4      500
5      500

I need a query to find the max(s_no) according to the sum(amount)
For e.g. when sum(amount)<=1600 i need 4 as result.I can get the desired output by using cursor but it would be easier if i could use query.. I tried a query as follows:

SELECT MAX(s_no) from table HAVING SUM(amount)<=1600

But it doesn't work. I would appreciate any kind of help.
Thank you.

Best Answer

select  min(s_no)   as s_no

from   (select  s_no 
               ,sum(amount) over (order by s_no) as running_total 

        from    mytable
        ) t 

where   running_total > 1600