简体   繁体   English

SQL 服务器:四舍五入并转换为 int(在 Select 内)

[英]SQL Server: round decimal number and convert to int (within Select)

I am using the following line within a Select which returns a number with decimals, eg 33.33333.我在 Select 中使用以下行,它返回一个带小数的数字,例如 33.33333。

How can I round this within the Select and convert to integers so that I don't have decimals, eg in the above example it should return 33?如何在 Select 中舍入它并转换为整数,这样我就没有小数,例如在上面的示例中它应该返回 33?

100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END) AS matchPercent

You can use ROUND function to round the value to integer: 您可以使用ROUND函数将值四舍五入为整数:

ROUND(INT, 100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END), 0) AS matchPercent

This will retain the type, eg rounded float will stay float . 这将保留类型,例如圆形float将保持float If you also need to return int data type (or other integer data types), you need to also convert it: 如果还需要返回int数据类型(或其他整数数据类型),还需要转换它:

CONVERT(INT, ROUND(INT, 100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END), 0)) AS matchPercent

使用round函数来舍入数字:

ROUND(100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END), 0) AS matchPercent

如果要先对数字进行舍入,然后将其转换为整数,则还可以将0.5添加到要转换为整数的数字。

Below statement rounds a decimal value to nearest integer下面的语句将十进制值四舍五入到最接近的 integer

ROUND(decimalvalue,0)

ROUND(number, decimals, operation)

Example例子

ROUND(94.503,0)

Result: 95结果:95

Example例子

ROUND(94.403,0)

Result: 94结果:94

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

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