我需要创建一个计算每个分支的帐户总和并进行比较的函数 分支平衡。
我试着这样做:
CREATE OR REPLACE FUNCTION t3() RETURNS TABLE(bb integer, sum integer) AS $$
BEGIN
FOR i IN 1..50 LOOP
BEGIN
SELECT bbalance FROM branch WHERE branchid = i
union
SELECT sum(balance) FROM account WHERE branch = i;
END;
END LOOP;
END;
$$ LANGUAGE plpgsql;
我现在有点困惑...我希望它返回一个包含2列的表:一个具有来自分支的bbalance值;第二个是该分支中每个余额的总和。
我需要一些可以使用select * from t3()
调用的内容。
这就是我在pgAdmin查询编辑器中写的内容:
CREATE OR REPLACE FUNCTION t3() RETURNS TABLE(bb integer, sum integer) AS $$
DECLARE
bal integer;
BEGIN
FOR i IN SELECT branchid FROM branch
LOOP
SELECT INTO bb bbalance FROM branch WHERE branchid = i;
SELECT INTO "sum" sum(balance) FROM account WHERE branch = i;
RETURN NEXT;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
错误是:
ERRORE: variabile del ciclo sulle righe deve essere una variabile di tipo row o record o una lista di variabili scalari
LINE 5: FOR i IN SELECT branchid FROM branch
^
********** Error **********
ERRORE: variabile del ciclo sulle righe deve essere una variabile di tipo row o record o una lista di variabili scalari
SQL state: 42601
Character: 119
意大利语 - 翻译是:
循环遍历行的循环变量必须是记录或行变量或标量变量列表。
答案 0 :(得分:3)
您需要设置表变量而不是RETURN NEXT
,例如
CREATE OR REPLACE FUNCTION t3() RETURNS TABLE(bb integer, sum integer) AS $$
DECLARE
i integer;
BEGIN
FOR i IN SELECT branchid FROM branch
LOOP
SELECT INTO bb bbalance FROM branch WHERE branchid = i;
SELECT INTO "sum" sum(balance) FROM account WHERE branch = i;
RETURN NEXT;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
但实际上,如果没有PL / PgSQL作为一个简单的GROUP BY来加入,所有这一切都可以更加干净地完成:
SELECT b.branchid, b.bbalance, coalesce(sum(a.balance), 0) AS acctbalance
FROM branch b LEFT OUTER JOIN account a ON (b.branchid = a.branch)
GROUP BY b.branchid;
BTW,“sum”是参数名称的不良选择,因为它是一种常用的内置聚合函数。