SQL多个开始日期到结束日期

时间:2015-01-28 11:30:00

标签: sql-server sql-server-2008-r2

我有一个包含以下格式的表格(我无法更改)

ClientID  |  RefAd1  |  Cluster Start Date  |  Cluster End Date

100001    |   R1234  |    2014-11-01        |     
100001    |   R1234  |    2014-11-10        |  
100001    |   R1234  |    2014-11-20        |

我想提出的是:

ClientID  |  RefAd1  |  Cluster Start Date  |  Cluster End Date

100001    |   R1234  |    2014-11-01        |     2014-11-10          
100001    |   R1234  |    2014-11-10        |     2014-11-20    
100001    |   R1234  |    2014-11-20        |     NULL

我在这里搜索过,并且自己做了很多尝试,但却无法让它发挥作用。

我无法更新源表(或将另一个表添加到数据库中)所以我将在视图中执行此操作(我可以保存)

任何帮助都会非常感激,并且已经围绕这一天进行了一天,现在有点了!

2 个答案:

答案 0 :(得分:1)

使用自我加入获取下一条记录

;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,*
    FROM YOURTABLE
)
SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 

编辑:

要更新表格,您可以使用以下查询

;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,*
    FROM #TEMP
)
UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date]
FROM
(
    SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
    FROM CTE C1
    LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 
)TAB
WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date]

编辑2:

如果您希望ClientIdRefAd1完成此操作。

;WITH CTE AS
(
    -- Get current date and next date for each type of ClientId and RefAd1
    SELECT ROW_NUMBER() OVER(PARTITION BY ClientID,RefAd1 ORDER BY [Cluster Start Date])RNO,*
    FROM #TEMP
)
UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date]
FROM
(
    SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
    FROM CTE C1
    LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 AND C1.ClientID=C2.ClientID AND C1.RefAd1=C2.RefAd1
)TAB
WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date] AND TAB.ClientID=#TEMP.ClientID AND TAB.RefAd1=#TEMP.RefAd1

如果您只想为ClientId执行此操作,请删除RefAd1

的条件

答案 1 :(得分:1)

如果你只想要你描述的视图,这是脚本:

CREATE VIEW v_name as
SELECT 
  ClientId, 
  RefAd1, 
  [Cluster Start Date], 
  ( SELECT 
      min([Cluster Start Date])
    FROM yourTable 
    WHERE 
      t.[Cluster Start Date] < [Cluster Start Date]
) as [Cluster End Date]
FROM yourtable t