对于SQL中的循环基础知识

时间:2012-09-17 20:00:56

标签: sql loops for-loop

当我第一次学习R时,我在处理重复性任务时发现了for循环的强大功能。现在,我想对SQL应用相同的逻辑,但我很难理解psql的基本原理。当我在Postgres工作时,任何ANSI解决方案都会非常感激。

问题是这个。我有一个名单。对于我想要生成报告的每个名称。我要查询的其中一个表格非常庞大,我不能简单地为所有名称运行我的脚本,然后只是单独过滤名称,所以我想做类似下面的事情:

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
}

1 个答案:

答案 0 :(得分:0)

这不是一个完整的答案,因为我没有耐心重新考虑你在代码中所做的所有事情,但简而言之,我认为你所寻找的是:

INSERT INTO name_print (...column names separated with commas...)
SELECT ...fields...
 FROM table1 ...all the joins...
 WHERE table1.name IN (...list of values or another select...);