SQL Server查询以合并日期

SQL Server查询以合并日期,sql,sql-server,sql-server-2005,tsql,Sql,Sql Server,Sql Server 2005,Tsql,我试图创建一个基于id加上代码加上开始日期的密钥,该日期跨越一系列日期并合并id+代码,直到出现另一个id+代码。以下是数据: ID CODE EFFECTIVE TERM 9950 H0504402 07/01/2007 08/31/2007 9950 H0504404 09/01/2007 01/31/2008 9950 H0504402 02/01/2008 01/21/2009 9950 H050

我试图创建一个基于id加上代码加上开始日期的密钥,该日期跨越一系列日期并合并id+代码,直到出现另一个id+代码。以下是数据:

ID CODE EFFECTIVE TERM 9950 H0504402 07/01/2007 08/31/2007 9950 H0504404 09/01/2007 01/31/2008 9950 H0504402 02/01/2008 01/21/2009 9950 H0504402 03/01/2009 01/21/2010 9950 H0504404 02/01/2010 02/11/2011 9950 H0504404 03/01/2011 NULL 我试图得到的结果是:

KEY EFFECTIVE TERM 9950_H0504402_20070701 07/01/2007 08/31/2007 9950_H0504404_20070901 09/01/2007 01/31/2008 9950_H0504402_20080201 02/01/2008 01/21/2010 9950_H0504404_20100201 02/01/2010 NULL SQLServer2005

任何帮助都是非常感谢的,像往常一样,在枪口下,在这一点上,大脑已经死亡。谢谢

declare @t table(id int, code char(8), effective datetime, term datetime)
insert @t values
(9950,    'H0504402',    '07/01/2007',    '08/31/2007'),
(9950    ,'H0504404'    ,'09/01/2007',    '01/31/2008'),
(9950    ,'H0504402'    ,'02/01/2008',    '01/21/2009'),
(9950    ,'H0504402'    ,'03/01/2009',    '01/21/2010'),
(9950    ,'H0504404'    ,'02/01/2010',    '02/11/2011'),
(9950    ,'H0504404'    ,'03/01/2011',    NULL)

;with cte as
(
-- add rownumber (rn)
select id, code, effective, term, row_number() over (order by effective) rn
from @t
), 
b as
(
-- add group (r)
select *, 1 r  from cte where rn = 1
union all
select cte.* , case when b.id <> cte.id or b.code <> cte.code 
then r + 1 else r end
from cte join b on b.rn + 1 = cte.rn
), 
c as
(
-- find last and first row
select id, code, min(effective) over (partition by r) effective, 
term, row_number() over (partition by r order by rn desc) nrn
,rn, r
from b
)
-- convert columns to look like description
select cast(id as varchar(9))+ code + '_' + convert(char(8), effective,112) [KEY], 
effective, term from c where nrn = 1 order by rn 
option (maxrecursion 0)-- added to prevent problems in a production environment
在此处测试:

我对结果感到困惑。为什么截止日期为2011年2月11日和2009年1月21日的记录没有返回?一开始,我以为您希望按键和代码显示此组,但我无法理解您返回的内容。如果某个术语日期与另一行具有相同ID和代码的生效日期重叠,会发生什么情况?是否所有日期范围都不重叠?K.R:结果是我希望看到的,但是我不知道如何使用SQL。L&M.S:EFFECTIVE+术语永远不会重叠。谢谢你,这对我提供的数据非常有效,如果我将表限制在100行左右,它也会起作用。我正在查询的特定表有150000多行;我的错是没有包括那个信息。当更改代码以使用该表时,我收到错误消息,语句终止。在语句完成之前,最大递归100已用尽。@CameronEckman在我添加最后一行之后,您是否对其进行了测试?从我的评论中可以看出,它应该可以解决您需要向下滚动的问题