简体   繁体   中英

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,

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

The salary that it returns is like 7787.000992213

How can i round the value?

If you want the number truncated, do this, using TRUNCATE :

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

If you want it rounded to the nearest integer, do this, using ROUND :

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

ROUND(X), ROUND(X,D) - Rounds the argument X to D decimal places

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.

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

Rounding just means to round up from 5 or down from anything less. ROUND is unique because you can tell SQL which position you would like rounded

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

Use MySQL's ROUND() function:

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:

ROUND(X), ROUND(X,D)

Rounds the argument X to D decimal places. The rounding algorithm depends on the data type of X. D defaults to 0 if not specified. D can be negative to cause D digits left of the decimal point of the value X to become zero.

使用圆形函数在这里阅读

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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