Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL divide two integers and get a decimal value error

In an SQL statement, I am trying to divide two integers (integer 1 is "abc" in my code below, integer 2 is "xyz" in my code), and get a result as a decimal (def in my code below). The decimal result should have a leading 1 or 0 only, followed by a decimal and 3 numbers after the decimal. However my code keeps returning a straight 0 with no decimals.

SELECT CONVERT(DECIMAL(4,3), abc/xyz) AS def

This code results in "0", when what I want is something like "0.001" or "0.963". I believe that it is still looking at "def" as an integer, and not as a decimal.

I have also tried using CAST on abc and xyz but it returns the same thing. I have also tried the following code:

SELECT CONVERT(DECIMAL(4,3), abc/xyz) AS CONVERT(DECIMAL(4,3)def)

But this gives me an error, saying there is a syntax error near the word "CONVERT".

like image 486
user2762748 Avatar asked Mar 22 '23 15:03

user2762748


2 Answers

Convert to decimal before the divide, not after. The convert for answer format.

SELECT 
  CONVERT( DECIMAL(4,3)
         , ( CONVERT(DECIMAL(10,3), abc) / CONVERT(DECIMAL(10,3), xyz) ) 
         ) AS def
like image 199
asantaballa Avatar answered Apr 02 '23 09:04

asantaballa


This should do it. Also add divide by zero check.

 SELECT CONVERT(DECIMAL(4,3), abc) / NULLIF(xyz,0)
like image 33
sam yi Avatar answered Apr 02 '23 09:04

sam yi