假设我有一个关系item,location,year,supplier,unit_sales
,我想写一个plpgsql
函数作为图像中查询的包装,指定参数N
,如下所示:
create or replace function iceberg_query( percentage integer )
returns cube
/* Code here */
as
$$
declare
numrows int;
begin
select count(*) into numrows from sales;
select item, location, year, count(*)
from sales
group by cube(item,location,year)
having count(*) >= numrows*percentage/100;
end;
$$ language 'plpgsql'
我需要添加到Code here
-part,以使其工作?如何在plpgsql
中将数据立方体指定为返回类型?
要使plpgsql函数正常工作,需要一个匹配返回的RETURNS
子句。你需要实际返回一些东西。我想:
CREATE OR REPLACE FUNCTION iceberg_query ( percentage numeric)
RETURNS TABLE (item ?TYPE?, location ?TYPE?, year ?TYPE?, ct bigint)
AS
$func$
DECLARE
numrows bigint := (SELECT count(*) FROM sales);
BEGIN
RETURN QUERY
SELECT s.item, s.location, s.year, count(*)
FROM sales s
GROUP BY cube(s.item,s.location,s.year)
HAVING count(*) >= numrows * percentage / 100;
END
$func$ LANGUAGE plpgsql;
将占位符?TYPE?
替换为实际(未公开)数据类型。
用以下方法调用函数:
SELECT * FROM iceberg_query (10);
请注意我如何对查询中的所有列名进行表限定,以避免使用相同名称的新OUT
参数命名冲突。
请注意numeric
指出的integer
而不是comment的使用。
有关:
旁白:你不需要这个功能。这个普通的SQL查询也是这样的:
SELECT s.item, s.location, s.year, count(*)
FROM sales s
GROUP BY cube(s.item,s.location,s.year)
HAVING count(*) >= (SELECT count(*) * $percentage / 100 FROM sales); -- your pct here
提供数字文字(10.0
,而不是10
)以避免整数除法及其附带的舍入。