I discovered the power of for loops when dealing with repetitive tasks when I first learned R. Now, I want to apply the same logic to SQL, but I am struggling to understand the fundamentals of psql. While I am working in Postgres any ANSI solution would be much appreciated.
The problem is this. I have a list of names. For each name I want to generate a report. One of the tables I am querying against is so superbly massive that I can't simply run my script for all names and then just filter on name alone, so I want to do something like below:
for(i in list){
select distinct name, key
into temp table stuff from table1 where name = i
select case when x.date is null then y.date else x.date end date
, widgets
, troll
, cookie
, googol
, bite
, clicks
into temp table junk2
from (
select substring(datetime,1,10) as date
, count(*) as bite
, count(distinct cookie) as cookie
, count(distinct troll) as troll
from table2
where order_key in (select key from stuff)
group by substring(datetime,1,10)
order by substring(datetime,1,10)
) x
full join (
select substring(datetime,1,10) as date
, count(distinct widgets) as widgets
, count(distinct googol) as googol
, count(*) as clicks
from table3
where order_key in (select key from stuff)
group by substring(datetime,1,10)
order by substring(datetime,1,10)
) y
on x.date = y.date
COPY junk2 to name_print(i) --psuedocode
discard all
}
datetime
a string type or a timestamp type? You really shouldn't be storing date/time values as string, or using string functions on them. – Clockwork-Muse Sep 17 '12 at 22:02COPY junk2 to name_print(i)
. – a_horse_with_no_name Sep 18 '12 at 13:13