SQL来合并日期
我有以下数据:SQL来合并日期,sql,sql-server-2008,Sql,Sql Server 2008,我有以下数据: 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 2
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
我想不出一个好办法。一个方法就是忽略
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
值排在最后。如果将来有日期,则需要使用不同的表达式。将状态添加到分组依据中。无论如何,您需要调整您的查询,因为它会在@lad2025生成不同的结果:为什么在orderby语句中添加“、2”?为什么直到我在订单中插入“、2”后,这才起作用?@lad2025。我没有关注最终结果集的实际顺序。添加的正确内容是日期,而不是状态(至少我认为状态名称的顺序与它们在数据中的顺序是一致的)。因此,请告诉我当聚合函数和GROUP BY子句中不包含status
时,它如何工作?我将max(status)放在我的select中。似乎给了我想要的。