SQL Server查询以合并日期

时间:2011-09-27 13:57:37

标签: 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    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

SQL Server 2005。

任何帮助都非常受欢迎,像往常一样在枪口下,并且在此死亡。感谢。

1 个答案:

答案 0 :(得分:3)

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

在这里测试: http://data.stackexchange.com/stackoverflow/q/113660/