在多行

时间:2016-11-14 23:22:21

标签: postgresql

我正在尝试将PERFORM用于返回多行的WITH查询。

CREATE OR REPLACE FUNCTION test_function() RETURNS void AS $$

BEGIN

PERFORM (
WITH selection AS (
    SELECT id,
    ROW_NUMBER() OVER w AS r,
    first_value(id) OVER w AS first_value,
    nth_value(id, 5) OVER w AS last_value
    FROM mytable
    WINDOW w AS (PARTITION BY v.ability_id ORDER BY unit_id ASC)
)
create_question(id, 1, 1, 1) 
FROM selection
WHERE ability_id IN (
    SELECT ability_id
    FROM selection
    WHERE last_value > 0.5
    ORDER BY first_value DESC
)
AND selection.r <= 5
);

END;
$$ LANGUAGE plpgsql;

我收到错误:

ERROR:  more than one row returned by a subquery used as an expression

postgres doc说不能这样做:

  

对于WITH查询,请使用PERFORM,然后将查询放在括号中。 (在这种情况下,查询只能返回一行。)

除了编写With查询(这里称为选择)两次之外,还可以做些什么来解决这个问题?

1 个答案:

答案 0 :(得分:2)

备注:您的查询在SELECT之前缺少create_question(id, 1, 1, 1)

诀窍是修改查询,使其返回单行。

您可以使用聚合函数来完成此操作,例如写:

SELECT
   count(create_question(id, 1, 1, 1))
FROM selection
...

然后查询只返回一行,可以在PERFORM语句中用作子查询。