【问题标题】:Loop through table1, extract information from table2 and insert into table3 in Teradata遍历table1,从table2中提取信息并插入到Teradata中的table3中
【发布时间】:2021-04-09 15:41:20
【问题描述】:

我是 SQL 中控制结构的新手,我正在尝试遍历包含客户和日期信息的表,并根据日期列,找到该客户在接下来 7 天内的销售额并将其插入另一个桌子。这是我到目前为止所拥有的,但我认为 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();

【问题讨论】:

  • 请注意,“loop through”通常应该转换为“JOIN”。但要解决您的具体问题,请使用SELECT INTO 而不是SET

标签: sql teradata


【解决方案1】:

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)
;

看,没有循环,没有 proc,效率更高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2017-11-15
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    相关资源
    最近更新 更多