如何在循环中将结果导出为CSV

时间:2016-12-29 13:17:19

标签: sql database postgresql export-to-csv sql-scripts

我有一个SQL查询

class milk extends condimentDecorator{
public $beverage;
public function __construct(beverage $beverage){$this->beverage = $beverage;}
public function getDescription(){return $this->beverage->getDescription().", Milk";}
};

以下面的格式给出了结果:

       select time,t_count,sum(t_count) over (order by time) as
       cumulative_t_count ,cumulative_t_count/sum(t_count) as percentage_cumulative count,state,hour from (select distinct
       time,count(distinct num_id) as t_count,state,hour from (select * from
       public.table1 where day=1 and time>0 order by time)as A group by
       time,hour,state order by hour,state )B where state=1 and hour=1; 

同样我从0-23开始有80个状态和小时。我想通过改变状态从1-80和小时1,7,14,19将所有结果导出到CSV文件。所以现在我手动更改上述代码中的状态和小时,并将结果导出为CSV。但似乎我必须为每个州更改状态1到80和小时1,7,14,19。

time  t_count  cumulative_t_count  state  hour
_____ _____  _________________     ____  ____
1      10          10               1    1
2      20          30               1    1
3      30          60               1    1
4      60          120              1    1

但这不起作用。我也想以CSV格式导出每个结果集。非常感谢。

1 个答案:

答案 0 :(得分:1)

如果您只需要执行此操作一次,则可以使用以下命令创建所需的sql语句。然后,您可以复制输出记录并执行它们。

WITH states AS
(SELECT generate_series(1,80) as i),
hours AS
(SELECT j FROM (values (1),(14),(17),(19) ) s(j))
SELECT 'copy ( select time,t_count,sum(t_count) over (order by time) as
       cumulative_t_count ,cumulative_t_count/sum(t_count) as     percentage_cumulative count,state,hour from (select distinct
       time,count(distinct num_id) as t_count,state,hour from (select * from
       public.table1 where day=1 and time>0 order by time)as A group by
       time,hour,state order by hour,state )B where state=' ||i || ' and hour=' ||j || ')

     To ''/tmp/state_' ||i || '_hour_' ||j || '.csv'' With CSV;' from states,hours