[英]Loop through table1, extract information from table2 and insert into table3 in Teradata
我是 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();
弗雷德的評論全文:-)
但要解決您的具體問題,請使用 SELECT INTO not 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)
;
看 ma,沒有循環,沒有 proc,效率更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.