Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal values in SQL for dividing results

In SQL, I have col1 and col2. Both are integers.

I want to do like:

select col1/col2 from tbl1 

I get the result 1 where col1=3 and col2=2

The result I want is 1.1

I put round(col1/col2,2). The result is still 1.

I put decimal(col1/col2,2). The decimal is not built in function.

How can I do exactly to get 1.1?

like image 393
william Avatar asked Jan 29 '11 03:01

william


People also ask

How do you get the decimal value when dividing in SQL?

Answers. SELECT ( Cast (Col1 AS Float) / Cast (Col2 AS Float) ) AS [Value] FROM ..... SELECT CAST(Col1 as decimal(10,2)) / CAST(col2 as decimal(10,2)) as [Value] FROM ... SELECT ( Cast (Col1 AS Float) / Cast (Col2 AS Float) ) AS [Value] FROM .....

How do you divide in SQL query?

The SQL divide ( / ) operator is used to divide one expressions or numbers by another.

How do you specify decimals in SQL?

To store numbers that have fixed precision and scale, you use the DECIMAL data type. In this syntax: p is the precision which is the maximum total number of decimal digits that will be stored, both to the left and to the right of the decimal point. The precision has a range from 1 to 38.


2 Answers

Just another approach:

SELECT col1 * 1.0 / col2 FROM tbl1 

Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.

A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:

SELECT col1 * 1. / col2 FROM tbl1 

The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).

Principal advantage: less wordy than other approaches.

like image 200
Andriy M Avatar answered Oct 17 '22 19:10

Andriy M


You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx

For example

DECLARE @num1 int = 3 DECLARE @num2 int = 2  SELECT @num1/@num2  SELECT @num1/CONVERT(decimal(4,2), @num2) 

The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000

like image 34
Shiv Kumar Avatar answered Oct 17 '22 19:10

Shiv Kumar