我试图将记录或json存储到数组中并从函数中返回JSON:
CREATE OR REPLACE FUNCTION stat_per_day() RETURNS json AS $$
DECLARE
RR RECORD;
SS json[];
BEGIN
FOR RR IN (SELECT DISTINCT date
FROM timetable WHERE date<CURRENT_DATE ORDER BY date ASC)
LOOP
SELECT row_to_json(A) INTO SS FROM (SELECT RR.date as Dia, count(*) Total
FROM dates WHERE office_date=RR.date) A;
END LOOP;
RETURN json_agg(SS);
END; $$
LANGUAGE plpgsql;
错误:
ERROR: malformed array literal: "{"dia":"2017-07-24","total":228}"
DETAIL: Unexpected array element.
CONTEXT: PL/pgSQL function stat_per_day() line 8 at SQL statement
查询有点复杂,但想法是“保存”#34; json数组或记录数组中的每个forloop查询(我认为不存在)和循环之后,从数组中返回一个完整的json。
答案 0 :(得分:0)
你可能不需要循环循环吗?可以使用json_build_object
函数执行此任务,例如:
CREATE OR REPLACE FUNCTION stat_per_day() RETURNS json AS $$
DECLARE
SS json;
BEGIN
select json_agg(j order by (j->>'dia')::date) from (
SELECT json_build_object('dia', office_date, 'Total', count(*) ) as j
from dates
where
office_date in (SELECT date FROM timetable WHERE date<CURRENT_DATE)
group by office_date
) t
into SS;
RETURN SS;
END; $$
LANGUAGE plpgsql;