SQL Server:舍入十进制数并转换为 int(在 Select 内)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23154499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:40:16  来源:igfitidea点击:

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

sqlsql-serverselectintrounding

提问by user2571510

I am using the following line within a Select which returns a number with decimals, e.g. 33.33333.

我在 Select 中使用以下行,它返回一个带小数的数字,例如 33.33333。

How can I round this within the Select and convert to integers so that I don't have decimals, e.g. 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

回答by Szymon

You can use ROUNDfunction 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, e.g rounded floatwill stay float. If you also need to return intdata type (or other integer data types), you need to also convert it:

这将保留类型,例如 roundedfloat将保留float。如果您还需要返回int数据类型(或其他整数数据类型),则还需要对其进行转换:

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

回答by Guffa

Use the roundfunction to round the number:

使用round函数对数字进行四舍五入:

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

回答by Pim

If you want to round the number first and then convert it to an integer, you also can add 0.5 to the number that you want to convert to an integer.

如果您想先对数字进行四舍五入,然后将其转换为整数,您也可以在要转换为整数的数字上加上 0.5。