0

我想格式化這個查詢的結果:現在錯誤PLPGSQL功能:數組值必須以「{」或維度信息

CREATE OR REPLACE FUNCTION "alarmEventList"(sampleid integer 
          , starttime timestamp without time zone 
          , stoptime timestamp without time zone) 
RETURNS text[] AS 
$BODY$DECLARE 
result text[]; 
BEGIN 
select into result array_agg(res::text) 
from (
    select to_char("Timestamp", 'YYYY-MM-DD HH24:MI:SS') 
    ,"AlertLevel" 
    ,"Timestamp" - lag("Timestamp") over (order by "Timestamp") 
      from "Judgements" 
      WHERE "SampleID" = sampleid 
      and "Timestamp" >= starttime 
      and "Timestamp" <= stoptime 
     ) res 
    where "AlertLevel" > 0; 
    select into result array_to_string(result,','); 
return result; 
END 
$BODY$ 
LANGUAGE plpgsql VOLATILE 

沒有array_to_string()我得到的是這樣的:

{"(\"2013-10-16 15:10:40\",1,00:00:00)","(\"2013-10-16 15:11:52\",1,00:00:48)"} 

,我想是這樣的:

2013-10-16 15:10:40,1,00:00:00 | 2013-10-16 15:11:52,1,00:00:48 | 

但是當我運行查詢,我得到è RROR:

array value must start with "{" or dimension information 
+0

我已編輯你的問題幾次。請相應調整。添加您的Postgres版本,並避免在問題中提供「謝謝」提示。你可以在評論中提出工作答案,這也會告訴其他人是否適合你。 –

回答

1

你做需要的是一個數組類型,但字符串表示。 可以實現這樣的:

CREATE OR REPLACE FUNCTION "alarmEventList"(sampleid integer 
              , starttime timestamp 
              , stoptime timestamp 
              , OUT result text) AS 
$func$ 
BEGIN 

SELECT INTO result string_agg(concat_ws(',' 
         ,to_char("Timestamp", 'YYYY-MM-DD HH24:MI:SS') 
         ,"AlertLevel" 
         ,"Timestamp" - ts_lag) 
        , ' | ') 
FROM (
    SELECT "Timestamp" 
     ,"AlertLevel" 
     ,lag("Timestamp") OVER (ORDER BY "Timestamp") AS ts_lag 
    FROM "Judgements" 
    WHERE "SampleID" = sampleid 
    AND "Timestamp" >= starttime 
    AND "Timestamp" <= stoptime 
    ) res 
WHERE "AlertLevel" > 0; 

END 
$func$ LANGUAGE plpgsql 

手冊上string_agg()concat_ws()

+0

甜!!!,謝謝 –

相關問題