我正在尝试编写一个函数,该函数以新的数据类型返回来自两个不同行的数据。
这是我到目前为止所做的:
CREATE TABLE foo(
dt DATE NOT NULL,
f1 REAL NOT NULL,
f2 REAL NOT NULL,
f3 REAL NOT NULL,
f4 REAL NOT NULL,
);
CREATE TYPE start_finish_type AS (start_f1 REAL, start_f2 REAL, start_f3 REAL, start_f4 REAL,
finish_f1 REAL, finish_f2 REAL, finish_f3 REAL, finish_f4 REAL);
CREATE FUNCTION fetch_begin_end_data(start_date DATE, finish_date DATE)
RETURNS start_finish_type AS $$
DECLARE
actual_start_date DATE;
actual_finish_date DATE ;
retval start_finish_type;
BEGIN
-- Select earliest row matching start_date
SELECT MIN(dt) INTO actual_start_date FROM foo WHERE dt >= start_date;
SELECT MIN(dt) INTO actual_finish_date FROM foo WHERE dt <= finish_date;
SELECT f1,f2, f3, f4 FROM foo WHERE dt = actual_start_date;
SELECT f1,f2, f3, f4 FROM foo WHERE dt = actual_finish_date;
-- How do I store the values obtained above and return them in the new type?
END
$$ LANGUAGE plpgsql;
我的问题是:如何修改函数以便从两个不同的行返回数据,并以新的数据类型返回它们?
答案 0 :(得分:0)
尝试:
CREATE or replace FUNCTION fetchbeginenddata(start_date DATE, end_date DATE)
RETURNS startfinishtype AS $$
DECLARE
actual_start_date DATE;
actual_finish_date DATE ;
retval startfinishtype;
BEGIN
-- Select earliest row matching start_date
SELECT MIN(dt) INTO actual_start_date FROM foo WHERE dt >= start_date;
SELECT MIN(dt) INTO actual_finish_date FROM foo WHERE dt <= finish_date;
SELECT (a.f1,a.f2, a.f3, a.f4,b.f1,b.f2, b.f3, b.f4)
FROM
(SELECT f1,f2, f3, f4 FROM foo WHERE dt = actual_start_date) a
JOIN
(SELECT f1,f2, f3, f4 FROM foo WHERE dt = actual_finish_date) b
ON true into retval;
return retval;
END
$$ LANGUAGE plpgsql;
当然要求这两个选择同时返回一行
<强>更新强> 正如@eurotrash所述,您可能希望显式命名复合类型属性以匹配顺序,例如:
INTO retval.start_f1, retval.start_f2, ...
不仅仅是
INTO retval;