1
使用SQL Server 2008推導開始和結束日期從日期範圍內特定記錄
我有一個創紀錄的數字,並與「中」和列「出」的數據與相關的一些日期它。 我想根據標準推導出他們的開始日期和結束日期。最短日期成爲開始日期,緊接着的下一個日期成爲結束日期。一個記錄可以有多個輸入和輸出。以下是一些示例查詢,嘗試了幾個選項但沒有任何成效。
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