在交叉表查询postgres中传递参数

时间:2017-02-02 05:59:18

标签: postgresql crosstab

如何在crosstab中的postgresql查询中传递参数。 请参考postgresql中的以下功能

create function sp_nextfollowup_count_byweek(_from timestamp without time zone,_to timestamp without time zone)
returns table(userid integer,username character varying,day1 bigint,day2 bigint,day3 bigint,day4 bigint,day5 bigint,day6 bigint,day7 bigint)as
$BODY$
BEGIN
return query
with cte as(
select * from crosstab($$
select  follow_up_by,next_follow_up_date,count(*) from sales_enquiry_follow_up where next_follow_up_date between _from and _to
group by follow_up_by,next_follow_up_date 
order by follow_up_by,next_follow_up_date$$,$$select date::timestamp without time zone
from generate_series(
  _from,
  _to,
  '1 day'::interval
) date$$)
as(id integer, dd bigint,dd1 bigint,dd2 bigint,dd3 bigint,dd4 bigint,dd5 bigint,dd6 bigint)
)
select cte.id,u.username,cte.dd,cte.dd1,cte.dd2,cte.dd3,cte.dd4,cte.dd5,cte.dd6 from cte left join users u on cte.id=u.id;

END;
$BODY$
language plpgsql;

我收到此错误column "_from" does not exist。如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

因为交叉表的参数只是字符串,所以必须直接包含参数:

$$
select  follow_up_by,next_follow_up_date,count(*) from sales_enquiry_follow_up where next_follow_up_date between $$ || quote_literal(_from) || $$ and $$ || quote_literal(_to) || $$
group by follow_up_by,next_follow_up_date 
order by follow_up_by,next_follow_up_date$$