Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 根据等级声明新变量和输入日期_Sql Server - Fatal编程技术网

Sql server 根据等级声明新变量和输入日期

Sql server 根据等级声明新变量和输入日期,sql-server,Sql Server,我想“清理”一个数据集并声明一个新变量,然后根据排名输入一个日期 我的数据集如下所示: +-----+--------------+------------+-------+ | ID | Start_date | End_date | Rank | +-----+--------------+------------+-------+ | a | May '16 | May '16 | 5 | | a | Jun '16 | Jul '16

我想“清理”一个数据集并声明一个新变量,然后根据排名输入一个日期

我的数据集如下所示:

+-----+--------------+------------+-------+
| 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和日期进行排名:

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)
    )   

假设您已经拥有问题中提供的数据集,这只是一个简单的self
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 |
+----+------------+------------+------+

发布您的预期输出,以便每个人都能轻松地提供帮助。谢谢-太好了