2017-05-05 45 views
0

我想“清理”数据集并声明新变量,然后根据等级输入日期。根据等级声明新变量和输入日期

我的数据集是这样的:

+-----+--------------+------------+-------+ 
| ID | Start_date | End_date | Rank | 
+-----+--------------+------------+-------+ 
| a | May '16  | May '16 |  5 | 
| a | Jun '16  | Jul '16 |  4 | 
| a | Jul '16  | Aug '16 |  3 | 
| a | Aug '16  | NULL '16 |  2 | 
| a | Sept '16  | NULL '16 |  1 | 
+-----+--------------+------------+-------+ 

我基本上要输入等级1的开始日期为2级的结束日期,或者说输入开始到5月底6(总是-1)。

写了下面的根据ID和日期选择为tempory表和等级:

SELECT 
    [Start_Date] as 'start' 
    ,[End_Date] as 'end' 
     ,[Code] as 'code' 
     ,[ID] as 'id' 
    ,rank() over (partition by [id] order by [Start_Date]) as 'rank' 
INTO #1 
FROM [Table] 
ORDER BY [id] 

其下面的部分是不工作...

DECLARE new_end 
BEGIN select [#1].[start] into new_end FROM [#1] 
WHERE (
    ([#1].[rank] = 1) 
    AND ([#1].[end] IS NULL) 
    ) 
+0

发表您的预计输出,这样每个人都可以轻松帮。 – Tomato32

回答

0

假设你已经有你的问题提供的数据集,这只是一个简单的自我join,不是吗?

declare @t table(ID nvarchar(1), Start_date date, End_date date, [Rank] int); 
insert into @t values ('a','20170501','20170501',5),('a','20170601','20170701',4),('a','20170701','20170801',3),('a','20170801',NULL,2),('a','20170901',NULL,1); 

select t1.ID 
     ,t1.Start_date 
     ,isnull(t1.End_date,t2.Start_date) as End_date 

     -- If you *always* want to overwrite the End_Date use this instead: 
     -- ,t2.Start_date as End_date 

     ,t1.[Rank] 
from @t t1 
    left join @t t2 
     on(t1.[Rank] = t2.[Rank]+1); 

输出:

+----+------------+------------+------+ 
| ID | Start_date | End_date | Rank | 
+----+------------+------------+------+ 
| a | 2017-05-01 | 2017-05-01 | 5 | 
| a | 2017-06-01 | 2017-07-01 | 4 | 
| a | 2017-07-01 | 2017-08-01 | 3 | 
| a | 2017-08-01 | 2017-09-01 | 2 | 
| a | 2017-09-01 | NULL  | 1 | 
+----+------------+------------+------+ 
+0

谢谢 - 多数民众赞成 – tj123