Question

I'm trying to format the results of this query:

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

Right now without array_to_string() I get something like this:

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

and I want something like this:

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

But when I run the query I get error:

array value must start with "{" or dimension information
Was it helpful?

Solution

You do not actually want an array type, but a string representation. Can be achieved like this:

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

The manual on string_agg() and concat_ws().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top