使用 Postgres 9.5 我构建了这个函数:
CREATE or REPLACE FUNCTION func_getratio_laglag(_numeratorLAG text, _n1 int, _denominatorLAG text, _n2 int, _table text)
RETURNS TABLE (date_t timestamp without time zone, customer_code text, index text, ratio real) AS
$BODY$
BEGIN
RETURN QUERY EXECUTE
'SELECT
date_t,
customer_code,
index,
(LAG('||quote_ident(_numeratorLAG)||',' || quote_literal(_n1)||') OVER W / LAG('||quote_ident(_denominatorLAG)||','|| quote_literal(_n2)||') OVER W) '
|| ' FROM ' || quote_ident(_table)
|| ' WINDOW W AS (PARTITION BY customer_code ORDER BY date_t asc);';
END;
$BODY$ LANGUAGE plpgsql;
该函数所做的只是让我能够从指定的表中选择 2 个不同的列,并根据不同的滞后窗口计算它们之间的比率。要执行上面的函数,我使用以下查询:
SELECT * FROM func_getratio_laglag('order_first',1,'order_last',0,'customers_hist');
这将返回一个带有列标签date_t
、customer_code
和index
的表ratio
。我一直在努力解决如何将比率输出为动态列标签。也就是说,我想让它取决于输入参数,例如,如果我运行上面的选择查询,那么我想要列标签date_t
、、customer_code
和。index
order_first_1_order_last_0
我被卡住了,有什么建议或提示吗?