我在postgres中有一个场景,我希望对两个字段进行简单的划分。
如果答案小于1,我希望答案返回1
SELECT a/b AS Answer
6/4 = 1.50
4/6 = 0.66
4/4 = 1.00
例如,如果使用上面的calc,我希望SQL为第二次计算返回值1.
答案 0 :(得分:1)
您可以使用CASE-WHEN
SELECT CASE
WHEN ans < 1
THEN 1
ELSE ans
END AS answer
FROM (
SELECT a / b::REAL AS ans
FROM num1
) t
或
SELECT CASE
WHEN a < b
THEN 1
ELSE a / b::REAL
END AS answer
FROM num1
答案 1 :(得分:1)
CREATE table testdata (a int,b int);
WITH data AS (
INSERT INTO testdata VALUES (6,4),(4,6),(4,4)
)
SELECT a,b,
CASE WHEN a/b::REAL < 1 THEN 1
ELSE a/b::REAL
END
FROM testdata;
答案 2 :(得分:1)
SELECT GREATEST(a/b, 1) AS Answer