如何在 PostgreSQL 查询中声明变量 [重复]
Posted
技术标签:
【中文标题】如何在 PostgreSQL 查询中声明变量 [重复]【英文标题】:How to declare a variable in PostgreSQL queries [duplicate] 【发布时间】:2017-04-21 02:14:36 【问题描述】:我正在努力在 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
【问题讨论】:
【参考方案1】: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);
【讨论】:
以上是关于如何在 PostgreSQL 查询中声明变量 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何在一个 PostgreSQL 查询中使用多个 WITH 语句?