简体   繁体   中英

SQL Server query to find last occurred number greater than 0. If there is no number greater than 0 then query should return 0

I have a data like below.

Case A:

Amount (column name)
------
0
0
450
890
0
0

Case B:

Amount (column name)
------
0
0
0
0
0
0
  • In case 'A', query should return 890
  • In case 'B' query should return 0

I am looking for a SQL Server query which returns the expected results.

Assuming you have an ordering, the simplest method might be:

select coalesce(max(amount), 0)
from (select top (1) amount
      from t
      where amount > 0
      order by <ordering column> desc
     ) t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM