Home > bash, Linux, PostgreSQL > PostgreSQL export csv from shell

PostgreSQL export csv from shell

I needed to get stats per minute for a SMS TV vote from 50 tables – one table per vote:

solution 1:

#!/bin/sh
op=2
op=3
ip="10.10.10.157"

# NO work - version 8.0.4 ...
# op=1
# ip="10.10.10.5"

dbname="vote_2012_01"
for num in `seq 1 50`
do
	if (( ${num} < 10 ))
	then
		num="0${num}"
	fi
	
echo "copy (
select 
'Pesen ${num}' as pesen
,operator_id as op
, count(*) as cntr 
, date_trunc('minute',intime) as minutes
from  vote_201201_${num}
where true 
and operator_id = ${op} 
group by minutes, op 
order by minutes, op
)
to stdout  with csv header
force quote pesen,minutes
;
" | psql -U me -h ${ip} ${dbname} -F , --no-align  > data.op.${op}.pesen.${num}.csv

done

==============================================================
solution 2 – copy(SQL) did not work at psql -v 8.0.4 on me

#!/bin/sh
# done by dragkh
op=2
op=3
ip="10.10.10.157"

#work - version 8.0.4 ...
op=1
ip="10.10.10.5"

dbname="vote_2012_01"

for num in `seq 1 50`
do
	if (( ${num} < 10 ))
	then
		num="0${num}"
	fi
	
echo "select
'\"Pesen ${num}\"' as pesen
,operator_id as op
, count(*) as cntr 
, '\"' || date_trunc('minute',intime) || '\"' as minutes
from  vote_201201_${num}
where true 
and operator_id = ${op} 
group by minutes, op 
order by minutes, op
;
" | psql -U me -h ${ip} ${dbname} -F , --no-align  > data.op.${op}.pesen.${num}.csv

done
Advertisements
Categories: bash, Linux, PostgreSQL
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: