2017-02-04 53 views
1

我有如下表:打圈CopyTo從查詢

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格式。」一個單獨的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
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;