Round *UP* to the nearest 100 in SQL Server

后端 未结 13 954
野性不改
野性不改 2020-12-25 11:18

Is it possible to easily round a figure up to the nearest 100 (or 1000, 500, 200 etc.) in SQL Server?

So:

720 -> 800
790 -> 800
1401 -> 1500

相关标签:
13条回答
  • 2020-12-25 11:25

    One option would be to use the CEILING() function like this:

    SELECT CEILING(@value/100.0) * 100
    

    You may need to convert your value to a decimal first depending on its type.

    0 讨论(0)
  • 2020-12-25 11:28

    For rounding Up to the nearest thousand, Please try the following:-

    select round(YourValue, -3)
    

    Cheers!!!!!

    0 讨论(0)
  • 2020-12-25 11:34

    This will work for the values with decimal also.

    select floor((ceiling (@value) + 99) / 100) * 100;

    0 讨论(0)
  • 2020-12-25 11:35

    In addition to Gray's answer, I'd use the following inline function:

    CREATE FUNCTION dbo.udf_RoundNearest
    (
    @Number bigint,
    @RoundNearest bigint,
    @Direction int
    )
    
    RETURNS TABLE AS 
    RETURN
    
    SELECT CASE WHEN @RoundNearest>=@Number THEN @Number
           ELSE
            (
                    (@Number + CASE 
                               WHEN @Direction = 0 --Round Down
                               THEN 0
                               ELSE CASE WHEN @Number % @RoundNearest = 0 THEN 0 ELSE @RoundNearest END
                               END) / @RoundNearest) * @RoundNearest
    
       END Number
    

    Parameter Definition:

    1. @Number - the number you need to round
    2. @RoundNearest 10th, 100th , 1000th etc
    3. @Direction 0-> round down, 1-> round up

    using the function:

    SELECT * FROM dbo.udf_RoundNearest (1965,100,1) --> 2000
    SELECT * FROM dbo.udf_RoundNearest (1359,100,0) --> 1300
    SELECT * FROM dbo.udf_RoundNearest (1999,10,0) --1990
    SELECT * FROM dbo.udf_RoundNearest (80,100,0) --> 80 (if the @number parameter is less or equal the @RoundNearest parameter the result will be the @number itself
    

    it can also be used as apply it versus a table such as:

    ;with tmp (Value) as
      (select 1236 union all select 6584 union all select 9999)
    
        select t.*, fn.Number
        from tmp t
        cross apply dbo.udf_RoundNearest (Value,100,0) fn
    
        /*Result Set
        Value   Number
        1236    1200
        6584    6500
        9999    9900*/
    
    0 讨论(0)
  • 2020-12-25 11:36

    A generic solution - Use MOD to find the last 100th place and then add 100 to the result.

    select (720 - MOD(720,100)) + 100 from dual;
    

    If you need the next 80th place, just replace any "100" with "80".

    0 讨论(0)
  • 2020-12-25 11:36

    This worked fine for me.

    Round(@value/100, 0) * 100

    0 讨论(0)
提交回复
热议问题