当我使用一个函数时,它会给出上面提到的错误,但当同一个代码单独使用时,它工作得很好。问题出在哪里?
摆弄功能:https://dbfiddle.uk/?rdbms=postgres_12&fiddle=c4b0c8a59d2bd851284ed624ab1c335d
摆弄干净选择:https://dbfiddle.uk/?rdbms=postgres_12&fiddle=7ccca6c70061aff1f6c394815aa8e9b1
样本数据:
create table report
(report_day date,
tickets_no integer,
tickets_stake numeric,
promo_tickets_no integer,
promo_tickets_stake numeric,
group_id integer);
insert into report
values
('2020-07-20',12,569.6, 2, 44,1),
('2020-07-20',61,2000, 5, 260,2),
('2020-07-21',35,1244.2, 11, 250,1),
('2020-07-21',100,2500.5, 29, 575,2),
('2020-07-22',66,2511.8, 23, 670,1),
('2020-07-22',125,3358.2, 50, 990,2);
CREATE OR REPLACE FUNCTION report(arguments json)
RETURNS json AS
$BODY$
DECLARE
dateFrom date;
dateTo date;
selectedType integer;
BEGIN
dateFrom := cast(arguments->>'dateFrom' as date);
dateTo := cast(arguments->>'dateTo' as date);
selectedType := cast(arguments->>'selectedType' as integer);
RETURN (
WITH full_data as (
with tickets as (
select
report_day
, sum(tickets_no) as tickets_no
, sum(tickets_stake) as tickets_stake
FROM report
WHERE selectedType = 0
AND report_day between dateFrom and dateTo
GROUP BY 1)
, promo_tickets as (
select
report_day
, sum(promo_tickets_no) as promo_tickets_no
, sum(promo_tickets_stake) as promo_tickets_stake
FROM report
WHERE selectedType = 1
AND report_day between dateFrom and dateTo
GROUP BY 1)
select
t.report_day
, sum(coalesce(t.tickets_no,0) + coalesce(pt.promo_tickets_no,0)) as tickets_no
, sum(coalesce(t.tickets_stake,0) + coalesce(pt.promo_tickets_stake,0)) as tickets_no
FROM tickets t
LEFT JOIN promo_tickets pt on t.report_day = pt.report_day
GROUP BY 1
ORDER BY 1)
select row_to_json(full_data) from full_data
);
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
select * from report(json_build_object('dateFrom', '2020-07-20', 'dateTo', '2020-07-22','selectedType', 0 ))
2条答案
按热度按时间20jt8wwn1#
如果希望函数像查询一样返回报表对象数组,请更改此部分:
要将行聚合到数组中,请执行以下操作:
如果希望函数返回多行,则需要进行两个更改:
而对于
return
:这里是最新的小提琴。
pzfprimi2#
因为您试图从只应返回一行的函数中返回多行。在函数中再添加一个参数,最好是一个主键列(我想
tickets_no
)例如并将查询重写为
并通过添加第二个参数来调用。
演示