Home> Database> SQL> body text

How to calculate division with decimals in SQL

下次还敢
Release: 2024-04-28 11:33:13
Original
706 people have browsed it

The division operator in SQL automatically rounds. When decimals need to be retained, you can use the ROUND() function or explicitly convert the data type to floating point.

How to calculate division with decimals in SQL

SQL division preserving decimal method

In SQL, the division operator (/) will automatically operate on the result rounding. If you need to preserve decimals, you need to use theROUND()function or explicitly convert the data type.

Use ROUND() function

SELECT ROUND(x / y, 2) FROM table_name;
Copy after login
Copy after login

ROUND()The first parameter of the function is the value to be rounded, and the second parameter is the number of decimal places to round to. For example, the above query will retain two decimal places.

Explicit conversion of data types

Another way to preserve decimals is to explicitly convert the result to a floating-point data type, such asFLOATorDOUBLE. Floating-point data types can store decimals.

SELECT CAST(x / y AS FLOAT) FROM table_name;
Copy after login

Example

Consider the following table:

x y
10 3
##Execute the following query:

SELECT ROUND(x / y, 2) FROM table_name;
Copy after login
Copy after login
The result is :

x / y ##3.33 The query rounds the division result to two decimal places, and the result is 3.33.

The above is the detailed content of How to calculate division with decimals in SQL. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!