简体   繁体   English

SQL SERVER四舍五入到最接近的十分之一并取整

[英]SQL SERVER round up to the nearest tenth and to the whole number

I need to convert a calculation from VBS to Sql server to the whole number and the nearest tenth. 我需要将VBS到Sql Server的计算转换为整数和最接近的十分之一。 This is the calculation on VB: 这是在VB上的计算:

 a=2/28/2016
    b=6/15/2016
    d=1
    Days360(a, b) = 107
    -INT(-(10^d)*DAYS360(a,b)/30)/(10^d) =
    -INT(-(10^1)*107/30)/(10^1) =
    -INT(-10*107/30)/10 =
    -INT(-1070/30)/10 =
    -INT(-35.666667)/10 =
    -(-36)/10 =
    36/10 = 3.6 --- result for nearest tenth

a=2/28/2016
b=6/15/2016
d=0
Days360(a, b) = 107
-INT(-(10^d)*DAYS360(a,b)/30)/(10^d) =
-INT(-(10^0)*107/30)/(10^0) =
-INT(-1*107/30)/1 =
-INT(-107/30)/1 =
-INT(-3.5666667)/1 =
-(-4)/1 =
4/1 =4  ---result for the whole number

How do I convert these two to sql? 如何将这两个转换为sql? I use these two queries but I don't get the results I expected: 我使用了这两个查询,但没有得到预期的结果:

SELECT ROUND(DATEDIFF(day,'2016-02-28','2016-06-15')*10/30/10,0) AS DiffDate
SELECT ROUND(DATEDIFF(day,'2016-02-28','2016-06-15')*10/30/10,1) AS DiffDate

Some versions of SQL server have the following behaviour when dealing with literals: 在处理文字时,某些版本的SQL Server具有以下行为:

Any non-enclosed numeral with no decimal point is an integer constant . 没有小数点的任何非封闭数字都是integer constant When dividing two integers, the result is by default an integer, so the expression might get evaluated to 107 * 10 / 30 / 10 => 1070 / 30 / 10 => 35 / 10 => 3 with the usual precedence rules. 当将两个整数相除时,默认情况下结果是一个整数,因此使用通常的优先级规则,表达式的值可能会被计算为107 * 10 / 30 / 10 => 1070 / 30 / 10 => 35 / 10 => 3 Try using floating-point constants and observe the results. 尝试使用浮点常量并观察结果。 (Eg write 10.0 instead of 10 ) (例如,写10.0而不是10

See also this page for more information about constants: https://msdn.microsoft.com/en-us/library/ms179899.aspx . 另请参阅此页面以获取有关常量的更多信息: https : //msdn.microsoft.com/zh-cn/library/ms179899.aspx Or see this SO question: How to get a float result by dividing two integer values? 还是看到这样的问题: 如何通过将两个整数值相除来获得浮点结果?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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