SQL Select:在else条件中返回特定值

时间:2015-09-05 05:30:49

标签: postgresql

我在postgres中有一个场景,我希望对两个字段进行简单的划分。

如果答案小于1,我希望答案返回1

SELECT a/b AS Answer

6/4 = 1.50
4/6 = 0.66
4/4 = 1.00

例如,如果使用上面的calc,我希望SQL为第二次计算返回值1.

3 个答案:

答案 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

sqlfiddle

SELECT CASE 
        WHEN a < b
            THEN 1
        ELSE a / b::REAL
        END AS answer
FROM num1

sqlfiddle

答案 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