循环遍历 table1,从 table2 中提取信息并插入到 Teradata 中的 table3

Loop through table1, extract information from table2 and insert into table3 in Teradata

我是 SQL 中控制结构的新手,我正在尝试遍历包含客户和日期信息的 table,并根据日期列查找该客户的销售额在接下来的 7 天内将其插入另一个 table。到目前为止,这是我所拥有的,但我认为 set 语句不适用于 select:

create procedure proc()
   for cust_cursor as cc cursor for 
       select customer, date_dt from table1
   do
       set sales = (
             select sum(sales_amt) from table2 
             where customer = cust_cursor.customer and date_dt between cust_cursor.date_dt and (interval '7' day + cust_cursor.date_dt)
                   )
       insert into table3 values (cust_cursor.customer, sales)
   end for;

call proc();

Fred 的完整评论:-)

但要解决您的具体问题,请使用 SELECT INTO 而不是 SET

   do
         select sum(sales_amt) INTO sales from table2 
         where customer = cust_cursor.customer and date_dt between cust_cursor.date_dt and (interval '7' day + cust_cursor.date_dt)

请注意,“循环”通常应转换为“JOIN”。

insert into table3 (cust_cursor.customer, sales)
select t1.customer, sum(t2.sales_amt) 
from table1 as t1
join table2 as t2
  on t2.customer = t1.customer
 and t2.date_dt between t1.date_dt and (interval '7' day + t1.date_dt)
;

你看,没有循环,没有过程,效率更高。