當我第一次學習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
}
你應該避免SQL中的循環。查詢引擎針對基於集合的操作進行了優化,這是您應該使用的。循環是SQL中的一個性能殺手。 – Oded
除非絕對必要,否則您還應該避免使用臨時桌子! – xception
我必須問,列'datetime'是一個字符串類型還是時間戳類型?你真的不應該將日期/時間值存儲爲字符串,或者使用字符串函數。 –