从特定记录的日期范围中导出开始日期和结束日期

时间:2016-03-29 19:04:57

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

  

使用SQL Server 2008

我有一个记录编号和一个列中的''和' out'包含与之相关的日期的数据。 我想根据标准推导出他们的开始日期和结束日期。最小日期成为开始日期,立即下一日期成为结束日期。单个记录可以有多个输入和输出。这里的示例查询尝试了几个选项,但没有任何效果。

IF OBJECT_ID('tempdb..#tmp_Info') IS NOT NULL DROP TABLE #tmp_Info
IF OBJECT_ID('tempdb..#RN') IS NOT NULL DROP TABLE #RN

CREATE TABLE #tmp_Info
(
RECORD_NO           INT, 
TYPE_1          VARCHAR(10), 
TYPE_2          VARCHAR(250), 
START_END           DATE
)


INSERT INTO #tmp_Info (RECORD_NO, TYPE_1, TYPE_2, START_END)

VALUES
(261505,'IN','ADM','1/1/2001'),
(261505,'OUT','RELEASE','2/6/2001'),
(261505,'IN','ADM','2/10/2001'),
(261505,'OUT','RELEASE','4/2/2001'),
(261505,'IN','ADM','5/12/2001'),
(261505,'OUT','RELEASE','7/13/2001'),
(261506,'IN','ADM','1/12/2001'),
(261506,'OUT','RELEASE','2/15/2001'),
(261506,'IN','ADM','2/20/2001'),
(261506,'OUT','RELEASE','4/2/2001'),
(261506,'IN','ADM','5/15/2001'),
(261506,'OUT','RELEASE','7/17/2001'),
(261506,'IN','ADM','8/1/2001')

SELECT * FROM #tmp_Info;

-->>>> OPTION 1
WITH STARTEND AS
(
SELECT T.RECORD_NO, T.START_END, RN = ROW_NUMBER() OVER (PARTITION BY RECORD_NO, TYPE_1 ORDER BY START_END) 
FROM #tmp_Info T
)
SELECT A.RECORD_NO,A.START_END AS START_DT, B.START_END AS END_DT
FROM STARTEND A
LEFT JOIN STARTEND B ON A.RECORD_NO = B.RECORD_NO AND A.RN = B.RN+1
ORDER BY A.RECORD_NO, A.START_END;

-->>>>OPTION 2

SELECT T.*, RN = ROW_NUMBER() OVER (PARTITION BY RECORD_NO, TYPE_1  ORDER BY START_END)
into #RN 
FROM #tmp_Info T

SELECT * FROM #RN

我正在附加我正在寻找的结果集:enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

;WITH CTE_Rn AS (
   SELECT RECORD_NO, TYPE_1, TYPE_2, START_END,
          ROW_NUMBER() OVER (PARTITION BY RECORD_NO, TYPE_1 
                             ORDER BY START_END) AS rn
   FROM #tmp_Info
)
SELECT t1.RECORD_NO, t1.START_END AS START_DT, t2.START_END AS END_DT           
FROM CTE_Rn AS t1
LEFT JOIN CTE_Rn AS t2
ON t1.RECORD_NO = t2.RECORD_NO AND    
   t2.TYPE_1 = 'OUT' AND
   t1.rn = t2.rn
WHERE t1.TYPE_1 = 'IN';