indiguy
indiguy

Reputation: 504

Displaying decimals as fractions using SQL

I need to write a SELECT query for some users that will return a ratio. The math involved would just be the simple division of two numbers. However, they would like to have the ratio presented as a fraction rather than as a decimal. What is the best way to do that in SQL using Oracle 10g?

Upvotes: 1

Views: 3093

Answers (1)

Andrey Adamovich
Andrey Adamovich

Reputation: 20683

You can define a function in Oracle to calculate greatest common divisor (taken from here):

CREATE FUNCTION gcd (x INTEGER, y INTEGER) RETURN INTEGER AS
   ans INTEGER;
BEGIN
   IF (y <= x) AND (x MOD y = 0) THEN
      ans := y;
   ELSIF x < y THEN 
      ans := gcd(y, x);  -- Recursive call
   ELSE
      ans := gcd(y, x MOD y);  -- Recursive call
   END IF;
   RETURN ans;
END;

And then use that function in your SQL to concatenate a fraction string:

SELECT CAST(TRUNC(A / GCD(A, B)) AS VARCHAR2(10)) 
       || ' / ' || 
       CAST(TRUNC(B / GCD(A, B)) AS VARCHAR2(10)) AS FRACTION FROM TABLE

Upvotes: 10

Related Questions