sql - 根据条件将 Rowdata 转换为多行
问题描述
我正在尝试根据日期从单个列中提取父 ID 和子 ID
Cust_id ID Date
75407014 603 2018-04-27
79807014 603 2018-04-30
75407016 604 2018-04-23
79807016 604 2018-04-30
75407018 605 2018-04-24
79807018 605 2018-04-30
75407020 606 2018-04-24
79807020 606 2018-04-30
75407014 608 2018-04-27
我想排除 id = 608 因为只有一行,我执行的输出是指父子 ID
Select Row_number () over (partition by Cust_id, id order by date ) rn
我的预期输出:
Parent_id Child_id
75407014 79807014
75407016 79807016
75407018 79807018
75407020 79807020
因此,第一个日期的 Cust_id 将是 parent_id,下一个日期将是 child_id。ID 是 customer_id 的常用链接列
非常感谢您的帮助
解决方案
您可以使用lead
withpartition by id
来获得所需的输出。
对于 SQL Server 2012 及更高版本
select *
from (select [cust_id],
lead([cust_id])
over(partition by id order by date) as Child_id
from tablename t1)t
where child_id is not null
输出
+----------+----------+
| Cust_id | Child_id |
+----------+----------+
| 75407014 | 79807014 |
+----------+----------+
| 75407016 | 79807016 |
+----------+----------+
| 75407018 | 79807018 |
+----------+----------+
| 75407020 | 79807020 |
+----------+----------+
对于旧版本的 SQL Server,您可以使用子查询来查找线索,如下所示。
select *
from (select [cust_id],
(select top 1 [cust_id]
from tablename t2
where t2.id = t1.id
and t2.date > t1.date
order by t2.date) as Child_id
from tablename t1)t
where child_id is not null
推荐阅读
- javascript - socket.io 连接的最佳实践
- javascript - 在 Heroku 上部署的 React Portfolio 不显示图像
- reactjs - React Hooks - 防止深度比较导致无限重新渲染
- twitter-bootstrap - 减少 bootstrap/primeng scss 导入足迹
- javascript - 如何更快地找出哪个 nodeunit 导致异步错误?
- javascript - Javascript在keyevent之后开始秒表
- python - 张量流。将图像从 PNG 转换为 JPEG
- typescript - 在标记的不相交联合上运行的通用函数 - 为什么这里需要类型规范?
- javascript - 如何使用对象文字中的方法访问 ID?
- javascript - 需要使用 Vanilla Javascript 隐藏/显示子菜单