1

当我第一次学习 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
}
4

1 回答 1

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...);
于 2012-09-17T20:10:01.047 回答