正如问题所示,我需要向上或向下舍入到最接近的20,除了0-14之外的数字,所有必须舍入到20,因为不允许零值。表格不需要更新新的值。现在我只管理了向上或向下舍入到最接近的100,如下所示:
CASE WHEN ROUND(number,-2)=0 THEN CAST(ROUND(number,-2)+100 AS DECIMAL(18, 0))
ELSE CAST(ROUND(number,-2) AS DECIMAL(18,0)) END AS [NUMBER]
答案 0 :(得分:5)
试试这个:
DECLARE @testValue Int = 35;
SELECT
CASE
WHEN @testValue BETWEEN 0 AND 14 THEN 20
ELSE ROUND((@testValue * 1.0) / 20, 0) * 20
END MyRoundedValue;
可能有更优化的方法,但这是第一个想到的解决方案。 * 1.0
是强制转换为浮点数,以便/ 20
生成小数结果。结果使用ROUND
四舍五入,然后乘以20
得到最终的“舍入”值。
已编辑将0-14
的特殊情况考虑在内......
答案 1 :(得分:2)
这将有效:
--N = Your nearest number
--X = Number to round
SELECT ROUND(X/N, 0) * N
示例用法:
DECLARE @numberToRound INT;
SET @numberToRound = 25;
CASE WHEN @numberToRound BETWEEN 0 AND 14 THEN
20
ELSE
ROUND((CAST(@numberToRound AS DECIMAL) / 20.00), 0) * 20
END
答案 2 :(得分:0)
我更喜欢整数除法 * ,如果number
是整数,我的解决方案可能是这样的:
CASE
WHEN number BETWEEN 0 AND 14 THEN 20 /* actually, it seems to make more sense
to have the range as BETWEEN 0 AND 9,
because values from 10 to 14 would be
converted to 20 with the ELSE branch
anyway */
ELSE (number + 10) / 20 * 20
END
* 当两个操作数都是整数时,SQL Server使用整数除法。