在FUNCTION中的PostgreSQL 9.5 IF-THEN-ELSE不可用?

时间:2016-02-27 15:43:29

标签: postgresql

我的问题

在我的 PostgreSQL 数据库中尝试CREATE FUNCTION版本 9.5 时,我收到以下错误:

ERROR:  syntax error at or near "IF"
LINE 3:   IF strpos(trem_outcome, 'VALIDATED') = 0 THEN

这是我正在谈论的FUNCTION

CREATE OR REPLACE FUNCTION countValid(outcome text) RETURNS integer AS $$
    BEGIN
        IF strpos(outcome, 'VALIDATED') = 0 THEN
            RETURN 1;
        END IF;
        RETURN 0;
    END
$$ LANGUAGE SQL

我这里看不到IF-THEN-ELSE控制语句,虽然我在FUNCTION右边?

我错过了什么?

某些背景

我最终想要了解大量数据sum(countValid()),如下所示:

SELECT
    table1.tbl1_pk,
    count(table2.tbl2_outcome) as registered,
    sum(countValid(table2.tbl2_outcome)) as validated
FROM table1 JOIN table2 ON table2.tbl2_tbl1_fk = table1.tbl1_pk
GROUP BY table1.tbl1_pk;

我的表格如下:

+---------------------------------------+
|                 table1                |
+---------------+-----------------------+
| tbl1_pk (int) | tbl1_other_crap (w/e) |
+---------------+-----------------------+
| 1             | ...                   |
| 2             | ...                   |
| 3             | ...                   |
+---------------+-----------------------+

+------------------------------------------------+
|                    table2                      |
+---------+-----------------------+--------------+
| tbl2_pk | tbl2_tbl1_fk          | tbl2_outcome |
| (int)   | (int -> tbl1.tbl1_pk) | (text)       |
+---------+-----------------------+--------------+
| 1       | 1                     | VALIDATED    |
| 2       | 1                     | FLUNKED      |
| 3       | 3                     | VALIDATED    |
| 4       | 3                     | VALIDATED    |
| 5       | 1                     | FLUNKED      |
| 6       | 2                     | VALIDATED    |
| 7       | 3                     | VALIDATED    |
+---------+-----------------------+--------------+

我希望得到以下结果:

+---------------+------------------+-----------------+
| tbl1_pk (int) | registered (int) | validated (int) |
+---------------+------------------+-----------------+
| 1             | 3                | 1               |
| 2             | 1                | 1               |
| 3             | 3                | 3               |
+---------------+------------------+-----------------+

最小可重现的例子

我可以用更简单的函数重现我的问题:

CREATE OR REPLACE FUNCTION countValid(outcome text) RETURNS integer AS $$
    BEGIN
        IF 1 = 1 THEN
            RETURN 1;
        END IF;
        RETURN 0;
    END
$$ LANGUAGE SQL

...触发:

ERROR:  syntax error at or near "IF"
LINE 3:   IF 1 = 1 THEN

我对完全不同的方法持开放态度,但我宁愿让我的工作在一次查询中执行。

1 个答案:

答案 0 :(得分:0)

您不需要该功能。只需使用

count(table2.tbl2_outcome = 'VALIDATED' or null)