使用表

时间:2015-08-10 18:29:45

标签: sql postgresql view

在PostgreSQL中,我有一个名为cap_output的下表,其中有三列:

 case_id  | libcap | libcap_android | 
----------+--------+-----------------
 06112301 |   72.6 |           75.6 |

现在我想基于cap_output表中的第2和第3列创建一个View。视图将有三列。第二列diff将是libcaplibcap_android之间的差异。如果TRUE的绝对值小于0.5,则第三列为diff,否则为FALSE。所以我使用以下语句来创建视图

CREATE VIEW score_diff AS 
    SELECT c.case_id, 
    c.libcap - c.libcap_android AS diff, 
    (CASE WHEN abs(diff) < 0.5 THEN TRUE ELSE FALSE END) AS pass
    FROM cap_output AS c;

但是在创建此视图后,当我查询视图score_diff时,我得到了以下结果

 case_id  | diff | pass 
----------+------+------
 06112301 |   -3 | t

显然,差异是-3,它应该在视图的FALSE (f)列中返回pass。但它返回了TRUE (t)。那么为什么我会得到错误的结果?

2 个答案:

答案 0 :(得分:2)

这表明cap_output有一个名为diff的列。正如Marc指出的那样,视图会出现语法错误。

所以,重复逻辑:

CREATE VIEW score_diff AS 
    SELECT c.case_id, 
           (c.libcap - c.libcap_android) AS diff, 
           (CASE WHEN abs(c.libcap - c.libcap_android) < 0.5 THEN TRUE ELSE FALSE END) AS pass
    FROM cap_output AS c;

答案 1 :(得分:1)

您无法在选择列表中使用diff。此外,case不是必需的。试试这个:

CREATE VIEW score_diff AS 
    SELECT c.case_id, 
    c.libcap - c.libcap_android AS diff, 
    abs(c.libcap - c.libcap_android) < 0.5 AS pass
    FROM cap_output AS c;