R을 처음 배웠을 때 반복적 인 작업을 처리 할 때 for 루프의 힘을 발견했습니다. 이제 SQL에 동일한 로직을 적용하고 싶지만 psql의 기본 사항을 이해하려고 애 쓰고 있습니다. Postgres에서 작업하는 동안 ANSI 솔루션을 많이 사용하게 될 것입니다.For Loop Basics in 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' 열이 문자열 유형이나 타임 스탬프 유형입니까? 날짜/시간 값을 문자열로 저장하거나 문자열 함수를 사용해서는 안됩니다. –