plpgsql 错误:RETURN 在返回 void 的函数中不能有参数

zim*_*ima 5 sql syntax for-loop plpgsql postgresql-9.2

我正在尝试提取与特定日期和 user_ids 对应的记录计数,这些记录在数据库中的下一个日期没有对应的 user_ids。这是我试图完成它的方式(使用 plpgsql 但不定义函数:

    DO
    $BODY$
    DECLARE
        a date[]:= array(select distinct start_of_period from monthly_rankings where balance_type=2);
        res int[] = '{}';
    BEGIN
        FOR i IN array_lower(a,1) .. array_upper(a,1)-1
        LOOP
            res:=array_append(res,'SELECT COUNT(user_id) from (select user_id from monthly_rankings where start_of_period=a[i] except select user_id from monthly_rankings where start_of_period=a[i+1]) as b');
                    i:=i+1;
            END LOOP;
            RETURN res;
        $BODY$ language plpgsql
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:无法检索结果:错误:RETURN 不能在返回 void LINE 11: RETURN res; 的函数中有一个参数。我是这种程序语言的新手,无法发现该函数返回 void 的原因。我确实将值分配给了变量,并且我声明了空数组,而不是 NULL 数组。是否有语法或更重要的推理错误?

Erw*_*ter 6

1)你不能RETURN从一个DO声明在所有。你将不得不CREATE FUNCTION改为。

2.) 你不需要任何这些。使用这个查询,它会快一个数量级:

WITH x AS (
   SELECT DISTINCT start_of_period
         ,rank() OVER (ORDER BY start_of_period) AS rn
   FROM   monthly_rankings
   WHERE  balance_type = 2
   )
SELECT x.start_of_period, count(*) AS user_ct
FROM   x
JOIN   monthly_rankings m USING (start_of_period)
WHERE  NOT EXISTS (
   SELECT 1
   FROM   x x1
   JOIN   monthly_rankings m1 USING (start_of_period)
   WHERE  x1.rn = x.rn + 1
   -- AND    m1.balance_type = 2 -- only with matching criteria?
   AND    m1.user_id = m.user_id
   )
-- AND balance_type = 2  -- all user_id from these dates?
GROUP  BY x.start_of_period
ORDER  BY x.start_of_period
Run Code Online (Sandbox Code Playgroud)

这包括最后一个 qualifying start_of_period,您可能希望像在 plpgsql 代码中一样排除它。