简体   繁体   English

如何在SQL中取整值?

[英]how to Round a value in SQL?

I'm learning database and I have a question, 我正在学习数据库,但有一个问题,

When I run the following query to give me 12 month Average Salary, 当我运行以下查询给我12个月的平均工资时,

SELECT `EmployeeNo`,(`Salary`/12,) as AverageSalary FROM Employee

The salary that it returns is like 7787.000992213 它返回的薪水像7787.000992213

How can i round the value? 我如何舍入价值?

If you want the number truncated, do this, using TRUNCATE : 如果您希望数字被截断,请使用TRUNCATE进行此操作:

SELECT `EmployeeNo`,TRUNCATE((`Salary`/12,),0) as AverageSalary FROM Employee

If you want it rounded to the nearest integer, do this, using ROUND : 如果要四舍五入为最接近的整数,请使用ROUND

SELECT `EmployeeNo`,ROUND(`Salary`/12,) as AverageSalary FROM Employee

ROUND(X), ROUND(X,D) - Rounds the argument X to D decimal places ROUND(X),ROUND(X,D) -将参数X舍入到D小数位

For your example: 例如:

SELECT `EmployeeNo`, ROUND(`Salary`/12) as AverageSalary FROM Employee

试试这个查询

SELECT `EmployeeNo`,ROUND(`Salary`/12,) as AverageSalary FROM Employee

The ROUND() function is used to round a numeric field to the number of decimals specified. ROUND()函数用于将数字字段四舍五入为指定的小数位数。

SELECT `EmployeeNo`, ROUND(`Salary`/12) as AverageSalary FROM Employee

Rounding just means to round up from 5 or down from anything less. 四舍五入只是指从5向下舍入或向下舍入。 ROUND is unique because you can tell SQL which position you would like rounded ROUND是唯一的,因为您可以告诉SQL您想舍入到哪个位置

SELECT ROUND( 1 );   /* returns 1 */
SELECT ROUND( 1.5 ); /* returns 2 */
SELECT ROUND( 1.4635, 1 ); /* returns 1.5 */

Use MySQL's ROUND() function: 使用MySQL的ROUND()函数:

SELECT 'EmployeeNo', ROUND('Salary'/12, 0) as AverageSalary FROM Employee

Alternatively, since you don't need any decimal places, you can bypass the second argument: 另外,由于不需要任何小数位,因此可以绕过第二个参数:

SELECT 'EmployeeNo', ROUND('Salary'/12) as AverageSalary FROM Employee

According to the docs , the ROUND() function accepts two arguments: the first is the number to be rounded, and the second optionally specifies the decimal place to round to: 根据docsROUND()函数接受两个参数:第一个是要四舍五入的数字,第二个可选地指定要舍入到的小数位:

ROUND(X), ROUND(X,D) ROUND(X),ROUND(X,D)

Rounds the argument X to D decimal places. 将参数X舍入到D小数位。 The rounding algorithm depends on the data type of X. D defaults to 0 if not specified. 舍入算法取决于X的数据类型。如果未指定,则D默认为0。 D can be negative to cause D digits left of the decimal point of the value X to become zero. D可以为负数,从而导致值X的小数点后的D位变为零。

使用圆形函数在这里阅读

SELECT `EmployeeNo`, ROUND(`Salary`/12,0) as AverageSalary FROM Employee

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

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