首页 > 解决方案 > 根据条件将 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 的常用链接列

非常感谢您的帮助

标签: sqlsql-serversql-server-2008

解决方案


您可以使用leadwithpartition 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 

DEMO

输出

+----------+----------+
| 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 

推荐阅读