如何获取前一行值 Teradata
How to get previous row values Teradata
我有以下格式的数据
Id Code Date Amount Type
101 B25 5/4/2020 0 C
101 A15 5/5/2020 0 D
101 D15 5/5/2020 0 D
102 B35 6/2/2020 0 C
102 A15 6/2/2020 D
我需要以下内容
Id Code Date Amount Type C_Date C_Amount
101 A15 5/5/2020 0 D 5/4/2020 0
102 A15 6/2/2020 D 6/2/2020 0
对于所有代码='A15',我需要上一行的日期和金额,其中类型='C'
我做到了
Select id, Amount, Date,
sum(Amount) over (partition by ID ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as
C_Amount,
Max(Date) over (partition by ID ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as
C_Date
from Table
where code='A15' or Type='C'
输出不是想要的
Id Code Date Amount Type C_Date C_Amount
101 A15 5/5/2020 0 D ***5/5/2020 0***
102 A15 6/2/2020 D ***6/2/2020 ***
感谢任何帮助
答案集与您的查询不匹配,它也会包含 'C' 行。
ROWS between UNBOUNDED PRECEDING and CURRENT ROW
是一个组和。
您需要 ROWS between 1 PRECEDING and 1 PRECEDNG
和一个 ORDER BY 来获取上一行的值。
最好切换到 LAG 或 LAST_VALUE,这更简单并且允许处理 'A15' 和前 'C' 行之间的额外行:
Select id, Amount, Date,
LAG(case when Type='C' then Amount end IGNORE NULLS)
over (partition by ID
order by date) as C_Amount,
LAG(case when Type='C' then date end IGNORE NULLS)
over (partition by ID
order by date) as C_Date
from Table
where code='A15' or Type='C'
qualify code='A15';
我有以下格式的数据
Id Code Date Amount Type
101 B25 5/4/2020 0 C
101 A15 5/5/2020 0 D
101 D15 5/5/2020 0 D
102 B35 6/2/2020 0 C
102 A15 6/2/2020 D
我需要以下内容
Id Code Date Amount Type C_Date C_Amount
101 A15 5/5/2020 0 D 5/4/2020 0
102 A15 6/2/2020 D 6/2/2020 0
对于所有代码='A15',我需要上一行的日期和金额,其中类型='C'
我做到了
Select id, Amount, Date,
sum(Amount) over (partition by ID ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as
C_Amount,
Max(Date) over (partition by ID ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as
C_Date
from Table
where code='A15' or Type='C'
输出不是想要的
Id Code Date Amount Type C_Date C_Amount
101 A15 5/5/2020 0 D ***5/5/2020 0***
102 A15 6/2/2020 D ***6/2/2020 ***
感谢任何帮助
答案集与您的查询不匹配,它也会包含 'C' 行。
ROWS between UNBOUNDED PRECEDING and CURRENT ROW
是一个组和。
您需要 ROWS between 1 PRECEDING and 1 PRECEDNG
和一个 ORDER BY 来获取上一行的值。
最好切换到 LAG 或 LAST_VALUE,这更简单并且允许处理 'A15' 和前 'C' 行之间的额外行:
Select id, Amount, Date,
LAG(case when Type='C' then Amount end IGNORE NULLS)
over (partition by ID
order by date) as C_Amount,
LAG(case when Type='C' then date end IGNORE NULLS)
over (partition by ID
order by date) as C_Date
from Table
where code='A15' or Type='C'
qualify code='A15';