sql - Retain values till there is a change in value in Teradata
问题描述
There is a transaction history table in teradata where balance gets changed only when there is a transaction Data as below:
Cust_id Balance Txn_dt
123 1000 27MAY2018
123 350 31MAY2018
For eg,For a customer(123) on May 27 we have a balance of 1000 and on May 31 there is a transaction made by the customer so balance becomes 350. There is no record maintained for May 28 to May 30 with same balance as on May 27 . I want these days data also to be there (With same balance retained and the date is incremented ) Its like same record has to be retained for rest of the days till there is a change in a balance done by the transaction . How to do this in teradata? Expected output:
Cust_id Balance Txn_dt
123 1000 27MAY2018
123 1000 28MAY2018
123 1000 29MAY2018
123 1000 30MAY2018
123 350 31MAY2018
Thanks Sandy
Hi Dnoeth. It seems to work, but can you let me know how to expand till a certain day for eg : till 30JUN2018 ?
解决方案
有几种方法可以得到这个结果,Teradata 中最简单的方法是利用时间序列扩展来进行周期:
WITH cte AS
(
SELECT Cust_id, Balance, Txn_dt,
-- return the next row's date
Coalesce(Min(Txn_dt)
Over (PARTITION BY Cust_id
ORDER BY Txn_dt
ROWS BETWEEN 1 Following AND 1 Following)
,Txn_dt+1) AS next_Txn_dt
FROM tab
)
SELECT Cust_id, Balance
,Last(pd) -- last day of the period
FROM cte
-- make a period of the current and next row's date
-- and return one row per day
EXPAND ON PERIOD(Txn_dt, next_Txn_dt) AS pd
如果您运行 TD16.10+,您可以将 替换MIN OVER
为简化的LEAD
:
Lead(Txn_dt)
Over (PARTITION BY Cust_id
ORDER BY Txn_dt)
推荐阅读
- python - 使用 cron 安排激活虚拟环境并启动 Django 服务器的 bash 脚本
- r - 删除“.”之后的列标题中的字符
- r - 以特定模式选择行(R,数据框)
- python - 为什么我在使用 Lambda 时会收到此错误?
- eigen3 - 将一个块从 Eigen::Matrix 复制到同一矩阵的另一个块时,会出现什么混叠问题?
- flask - Flask-Dance 在重定向时使用 localhost 而不是域
- reactjs - 如何使用 React 为 Bootstrap 启用切换
- php - 奇怪的 MySQL 通配符行为
- kubernetes - k8 Ingress 规则是否应该直接通过 helm 更新
- html - 使用 Angular JS 为 Google 工作表数据创建搜索框?