我正在努力在PostgreSQL查询中声明变量。有人可以帮我解决下面的问题吗?
declare CampaignID val INT;
select CampaignID = 6
select
result_code.description,
count (*) as count
from
history
left join result_code on result_code.result_code = history.result_code
where
campaign_id = CampaignID
and history.start_date_time between '2016-12-06 00:00:00' and '2016-12-06 23:00:00'
group by
result_code.description
答案 0 :(得分:0)
1)第一种方式(使用PL / pgSQL函数):
CREATE OR REPLACE FUNCTION MY_SELECT_FUNC(CampaignID integer)
RETURNS TABLE(res_description character varying(255), res_count integer) AS
$BODY$
BEGIN
for res_description, res_count
in
select
result_code.description,
count (*) as count
from history
left join result_code on result_code.result_code = history.result_code
where campaign_id = CampaignID
and history.start_date_time between '2016-12-06 00:00:00' and '2016-12-06 23:00:00'
group by result_code.description
loop
return next;
end loop;
END;$BODY$
LANGUAGE plpgsql VOLATILE;
然后你可以在sql中选择结果:
SELECT * from MY_SELECT_FUNC(6);
2)第二种方式(使用sql函数):
CREATE TYPE MY_SELECT_FUNC_RES AS (res_description character varying(255), res_count integer);
CREATE OR REPLACE FUNCTION MY_SELECT_FUNC(CampaignID integer)
RETURNS SETOF MY_SELECT_FUNC_RES AS
$$
select
result_code.description,
CAST(count(*) AS INTEGER)
from history
left join result_code on result_code.result_code = history.result_code
where campaign_id = CampaignID
and history.start_date_time between '2016-12-06 00:00:00' and '2016-12-06 23:00:00'
group by result_code.description
$$
LANGUAGE SQL;
然后你可以在sql中选择结果:
SELECT * from MY_SELECT_FUNC(6);