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 开发者_StackOverflowpresented as a fraction rather than as a decimal. What is the best way to do that in SQL using Oracle 10g?
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
精彩评论