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?
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 .....
The SQL divide ( / ) operator is used to divide one expressions or numbers by another.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With