2015-11-18 61 views
-1

,我有以下数据:SQL巩固日期

rasID changeDate changeDateEnd status 
11860 2015-09-08 2015-10-09  Active 
11860 2015-10-09 2015-10-19  Planning 
11860 2015-10-19 2015-10-19  Planning 
11860 2015-10-19 2015-11-18  Planning 
11860 NULL  2015-11-18  Planning 
11861 2015-09-08 2015-10-09  Planning 
11861 2015-10-09 2015-10-12  Requested 
11861 2015-10-12 2015-11-18  Planning 
11861 NULL  2015-11-18  Planning 

我想是这样,它看起来像这样巩固这一数据:

rasID changeDate changeDateEnd status 
11860 2015-09-08 2015-10-09  Active 
11860 2015-10-09 2015-11-18  Planning 
11861 2015-09-08 2015-10-09  Planning 
11861 2015-10-09 2015-10-12  Requested 
11861 2015-10-12 2015-11-18  Planning 

我想不出一个好办法去做这个。

回答

0

一种方法是忽略changeDateEnd并专注于changeDate。然后您想要合并相邻的行。这样做的

一种方法是使用行号与汇聚,东西很适合在SQL Server 2008中的区别:

select rasId, min(changeDate), max(changeDate), status 
from (select t.*, 
      (row_number() over (partition by rasId order by coalesce(changeDate, getdate())) - 
       row_number() over (partition by rasId, status order by coalesce(changeDate, getdate())) 
      ) as grp 
     from table t 
    ) t 
group by rasId, grp, 
order by rasId, min(changeDate); 

coalesce()的目的仅仅是为了确保NULL值走过去。如果你将来有日期,你会想要使用不同的表达式。

+0

将'status'添加到'Group BY'。无论如何,你需要调整你的查询,因为它会产生不同的结果https://data.stackexchange.com/stackoverflow/query/394721 – lad2025

+0

@ lad2025:你为什么把“,2”的顺序声明?为什么在我按顺序插入“,2”之前这不起作用? –

+0

@ lad2025。 。 。我没有专注于最终结果集的实际排序。要添加的是正确的日期,而不是状态(至少我认为状态名称的排序只与它们在数据中的排序相一致)。 –