如何在Teradata中实现滞后功能。

时间:2018-07-26 12:50:39

标签: sql teradata lag

输入:

I have my data as shown in the image below

输出:

enter image description here

我希望输出如下图所示。

在输出图像中,“ behind”中的4被评估为tot_cnt-tot,而“ behind”中的后续数字被评估为例如:2被评估为lag(behind)-tot&只要保留“ rank”同样,即使“落后”也应保持不变。

有人可以帮我在Teradata中实现吗?

2 个答案:

答案 0 :(得分:1)

您似乎想要:

select *, (select count(*) 
           from table t1 
           where t1.rank > t.rank
          ) as behind
from table t;

答案 1 :(得分:0)

我将汇总数据并执行以下操作:

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;

每个id提供一行,这对我来说意义更大。如果您想要原始数据行(无论如何都是重复的),可以join将其返回到表中。