2012-09-17 75 views
1

當我第一次學習R時,我發現了處理重複性任務時for循環的強大功能。現在,我想將相同的邏輯應用於SQL,但我一直在努力理解psql的基礎知識。雖然我在Postgres工作,但任何ANSI解決方案都將非常感謝。SQL中的循環基礎知識

問題是這樣的。我有一個名單。對於我想要生成報告的每個名稱。一個我查詢對錶的是如此巨大的寄望,我不能簡單地運行我的腳本所有的名字,然後就在名稱過濾獨自一人,所以我想要做的事象下面這樣:

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 
} 
+10

你應該避免SQL中的循環。查詢引擎針對基於集合的操作進行了優化,這是您應該使用的。循環是SQL中的一個性能殺手。 – Oded

+1

除非絕對必要,否則您還應該避免使用臨時桌子! – xception

+0

我必須問,列'datetime'是一個字符串類型還是時間戳類型?你真的不應該將日期/時間值存儲爲字符串,或者使用字符串函數。 –

回答

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...); 
+0

@ X-Zero日期目前以文本形式存儲,我可以做的不多。我把子字符串,所以我可以在白天進行連接,因爲它們當前處於YYYY-MM-DD hh:mm:ss格式。 – user1636475