2013-07-17 79 views
3

我想提取對應於特定日期和user_ids記錄的計數,這些記錄在數據庫中的下一個日期沒有相應的user_id。這是我想用PLPGSQL來完成它(但不是定義函數的方式: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 

我得到一個錯誤:無法檢索結果:ERROR:返回不能在函數中的參數返回void LINE 11:RETURN res; 我對這個程序語言很陌生,不知道爲什麼函數返回void,我把值賦給變量,並且聲明爲空 - 而不是NULL - 數組是否存在語法或更重要的推理錯誤?

回答

2

1.)你不能RETURNDO聲明在所有。您必須改爲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 

這包括最後合格start_of_period,您可能需要排除它就像在你PLPGSQL代碼。