我有下表:
writing_agent_number|agent_name |individual_sub_name
-------------------- ----------------- --------------------
300699 |J Todd Foster |Haash,matthew
300699 |J Todd Foster |Lea, Monique
300693 |Loran J Marmes |Jensen, Jeffrey A
300842 |Mattthew Atkinson|Castano, Karissa
300927 |Richard Melberg |Burk, Barbara
300694 |Ryan Moran |Moran, Maura C
300697 |Scott W Lange, Jr|Stewart, Allisia
我的目标:我想创建一个名为" agent_name的单独csv文件。[timestamp] .csv"其中agent_name是" agent_name"中的每个不同代理的代理的名称。列。
以下是我的内容 ,(请原谅我,我是sql的新手)我假设我缺少一个输入代理名称的变量,但我我不知道从哪里开始。任何帮助表示赞赏:
CREATE OR REPLACE FUNCTION get_commissions()
$func$
BEGIN LOOP
EXECUTE '
COPY
(SELECT
writing_agent_number AS "Writing Number"
,agent_name AS "Agent Name"
,indiv_sub_name AS "Client Name"
FROM rdf_nwh_ind
TO '/Users/ryanmoran/Downloads/agent_name.csv'
WITH CSV Delimiter ',' Header;
END LOOP;'
END
$func$ LANGUAGE plpgsql;
答案 0 :(得分:0)
CREATE OR REPLACE FUNCTION get_commissions() RETURNS bool AS $func$
DECLARE
v_agent_name text;
BEGIN
FOR v_agent_name IN SELECT DISTINCT agent_name FROM rdf_nwh_ind
LOOP
EXECUTE format($$COPY (
SELECT writing_agent_number AS "Writing Number",
agent_name AS "Agent Name",
indiv_sub_name AS "Client Name"
FROM rdf_nwh_ind
WHERE agent_name = %s
)
TO '/Users/Shared/%s.%s.csv'
WITH CSV Delimiter ',' Header$$,
quote_nullable(v_agent_name),
replace(v_agent_name, ' ', '_'),
to_char(now(), 'YYYY-DD-MM'));
END LOOP;
RETURN true;
END;
$func$ LANGUAGE plpgsql;