2017-06-15 78 views
1

我在我的PostgreSQL 9.5数据库中有一个表,它包含两列,即start_time(没有时区的时间戳)和像这样的值(记录)。PostgreSQL:如何将表格记录拆分/导出为年份切片(CSV)?

Start_time    Values 
2003-06-07 00:00:00  12 
2004-02-03 00:00:00  16 
2005-07-09 00:00:00  14 
2003-07-07 00:00:00  17 
2004-01-31 00:00:00  11 
2005-05-02 00:00:00  10 

对于START_TIME,我需要出口MY_TABLE记录,以便它生成CSV文件,每年片这样的(分开每年为记录在一个单独的CSV文件)。

预期输出:

results_2003.csv 
results_2004.csv 
results_2005.csv 
and so on... 

如何做到这一点?

+1

动态execute format使用copy命令是“比去年”由START_TIME的一年END_TIME当年确定的?另外,您无法单独使用SQL创建.csv文件 - 您需要使用某些客户端程序,并且针对您的问题的详细答案将取决于您使用的客户端程序。 –

+0

号码结束时间并不重要,因此我编辑了这个问题。记录需要根据start_year以CSV的形式每年分解一次。我在Windows 7 Enterprise(x64)版本上使用PostgreSQL 9.5。 –

+0

其实,他可以完全从Postgres内部完成。我会在一分钟后发布一个适用于Linux的答案。 – FuzzyChef

回答

2

在里面plpgsql DO block,例如为:

do $$ 
declare 
    y int; 
begin 
    for y in 
     select distinct extract(year from start_time) 
     from my_table 
    loop 
     execute format($ex$ 
      copy (
       select * 
       from my_table 
       where extract(year from start_time) = %1$s 
       ) 
      to '\data\%1$s.csv' 
      $ex$, y); 
    end loop; 
end $$; 
+0

工作就像一个魅力!谢谢一堆。 –

+0

该死的,你打我吧 – FuzzyChef

1

几种可能的替代方法可以做到这一点,我会用execsql.py(https://pypi.python.org/pypi/execsql/ - 免责声明:我写了它),这个脚本:

select distinct 
    extract(year from start_time) as start_year, 
    False as exported 
into temporary table tt_years 
from interval_table; 

create temporary view unexported as 
select * from tt_years 
where exported = False 
limit 1; 

-- !x! begin script export_year 
-- !x! select_sub unexported 
-- !x! if(sub_defined(@start_year)) 
    create temporary view export_data as 
    select * from interval_table 
    where extract(year from start_time) = [email protected]_year!!; 
    -- !x! export export_data to [email protected]_year!!.csv as csv 
    update tt_years 
    set exported = True 
    where start_year = [email protected]_year!!; 
    -- !x! execute script export_year 
-- !x! endif 
-- !x! end script 

-- !x! execute script export_year 

的X!令牌将metacommands标识为execsql,它允许循环(通过结束递归)并导出为CSV。