Do not input private or sensitive data. View Qlik Privacy & Cookie Policy.
Skip to main content

Announcements
Write Table now available in Qlik Cloud Analytics: Read Blog
cancel
Showing results for 
Search instead for 
Did you mean: 
mohitsharmaalexion
Contributor
Contributor

How to create fields using for loop with load statement

Hi,

I am trying to generate fields within a table for lag periods, but not sure what I am doing wrong here. What I want is to create a lag column with value of sales equal to previous period. Now here variable vMax_period is basically the maximum number assigned to the period. if at present I have 50 period, I want this table to have 49 lag columns.

My try:

 

 

 

 

for j=1 to $(vMax_Period)
     [SALES_LAGS]:
     Load
         KEY,
         PERIOD,
         If(KEY = PEEK('KEY',-$(j)),Peek('TOTAL_ORDER_QTY',-$(j))) as [lag_$(j)]
     resident SALES
     order by by KEY,PERIOD;
next j;

 

 

 

 

 

Labels (1)
1 Solution

Accepted Solutions
mohitsharmaalexion
Contributor
Contributor
Author

Found the issue with my problem. Basically I need to keep field TOTAL_ORDER_QTY in load statement otherwise I'll always get NULL. So correct script should be:

 

for j=1 to $(vMax_Period)
     [SALES_LAGS]:
     Load
         KEY,
         PERIOD,
         TOTAL_ORDER_QTY,
         If(KEY = PEEK('KEY',-$(j)),Peek('TOTAL_ORDER_QTY',-$(j))) as [lag_$(j)]
     resident SALES
     order by by KEY,PERIOD;
next j;

View solution in original post

2 Replies
micheledenardi
Specialist II
Specialist II

Just remove the square brackets [] from the field name:

 

[Periods]:
Load
   null() as Period_0
AutoGenerate(0);


for j=1 to 12
     Concatenate(Periods)
     Load
         $(j) as Period_$(j)
     AutoGenerate(1);
next j;
Drop Field Period_0;

2022-05-04 15_59_26-test _ Sistema di visualizzazione modello dati - Qlik Sense.png

Michele De Nardi
If a post helps to resolve your issue, please accept it as a Solution.
mohitsharmaalexion
Contributor
Contributor
Author

Found the issue with my problem. Basically I need to keep field TOTAL_ORDER_QTY in load statement otherwise I'll always get NULL. So correct script should be:

 

for j=1 to $(vMax_Period)
     [SALES_LAGS]:
     Load
         KEY,
         PERIOD,
         TOTAL_ORDER_QTY,
         If(KEY = PEEK('KEY',-$(j)),Peek('TOTAL_ORDER_QTY',-$(j))) as [lag_$(j)]
     resident SALES
     order by by KEY,PERIOD;
next j;