0

Input :

I have my data as shown in the image below

Output :

enter image description here

I want the output as shown in the image below.

In the output image, 4 in 'behind' is evaluated as tot_cnt-tot and the subsequent numbers in 'behind', for eg: 2 is evaluated as lag(behind)-tot & as long as the 'rank' remains same, even 'behind' should remain same.

Can anyone please help me implement this in teradata?

Swapnil Sudhir
  • 231
  • 1
  • 3
  • 11

2 Answers2

1

You appears to want :

select *, (select count(*) 
           from table t1 
           where t1.rank > t.rank
          ) as behind
from table t;
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
0

I would summarize the data and do:

select id, max(tot_cnt), max(tot),
       (max(tot_cnt) -
        sum(max(tot)) over (order by id rows between unbounded preceding and current row)
       ) as diff
from t
group by id;

This provides one row per id, which makes a lot more sense to me. If you want the original data rows (which are all duplicates anyway), you can join this back to your table.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786