将多个行折叠为一个带有标题的行

时间:2018-01-27 12:22:25

标签: sql-server

这是原始数据

id    title        hired_reason fired_reason hired_date     fired_date
xxxxx Asst Washer   abc           xyz        1992-01-01     2004-08-31 
xxxxx Asst Washer   def            sdhj      2004-09-01     2005-02-28 
xxxxx washer        ghi            hsgd      2005-03-01     2007-12-31 
xxxxx washer        jkl            hdhs      2008-01-01     2012-03-31 
xxxxx washer        mno            sgh       2012-04-01     2013-04-18 
xxxxx washer        pqr            tshsj     2013-05-21     2016-01-06 

我喜欢输出:

id    title        hired_reason fired_reason hired_date     fired_date
xxxxx Asst Washer   abc           sdhj      1992-01-01  2005-02-28 
xxxxx Washer        ghi           tshsj     2005-03-01  2016-01-06

我通过使用---

来实现这一目标
select id, min(hired_date), max(fired_date),seq
from (select ......,...,....
,row_number() over(order by hired_date) as line1
,row_number() over(partition by title ,order by hired_date) as line2 
,line1-line2 as seq
from table) table
 group by seq,id

所有测试用例运行良好但在一种情况下失败 原始数据

id  title hired_reason  fired_reason    hired_date  fired_date 
yyyy Wp     abc          hsdah          2017-01-01  2017-04-25 
yyyy W WP   def          shd            2017-04-26  2017-08-04 
yyyy Wp      ghi         jkl            2017-08-05  2017-10-20 
yyyy Mn     jkl          def            2017-10-21  2017-11-03 
yyyy Wp     mno          dfs            2017-11-04  2019-12-31 

输出我喜欢与原始数据相同但使用我的查询逻辑获得的数据如下

id  title hired_reason  fired_reason    hired_date  fired_date line1 line2 seq
yyyy Wp     abc          hsdah          2017-01-01  2017-04-25  1     1     0
yyyy W WP   def          shd            2017-04-26  2017-08-04  2     1     1
yyyy Wp      ghi         jkl            2017-08-05  2017-10-20  3     2     1
yyyy Mn     jkl          def            2017-10-21  2017-11-03  4     1     3
yyyy Wp     mno          dfs            2017-11-04  2019-12-31  5     3     2

我正在按seq进行分组并从分组数据中执行最小值和最大值我正在获取输出

id  title hired_reason  fired_reason    hired_date  fired_date
yyyy Wp     abc          hsdah          2017-01-01  2017-04-25 
yyyy W WP   def          shd            2017-04-26  2017-10-20
yyyy Mn     jkl          def            2017-10-21  2017-11-03 
yyyy Wp     mno          dfs            2017-11-04  2019-12-31 

在第二行中更改了fired_date,根据我的查询删除了第三行

先谢谢。

0 个答案:

没有答案