2017-06-01 41 views
1

我試圖抓取指定的所有行RowID,其中EffectiveDate與此不同。 但是,如果我們有多行使用相同的EffectiveDate,我想抓取所有其他行,並使用InsertDateTime列插入的最後一條記錄的日期相同。如果effectivedate與其他行相同,則獲取最新記錄

這裏是樣本數據:在這個例子中

enter image description here

所以,我在找的輸出是這樣的:

enter image description here

我們跳過與ID的行2 & & 3因爲它們的InsertDateTime小於第4行的InsertDateTime

我採取的方法是做一個datediffEffectiveDate之間,如果second0比他們是相同的值,我應該抓住最後一個記錄。但是,使用這種方法,由於我的join,它不會返回我的最後一條記錄。

我想我很複雜這個查詢。

CREATE TABLE #MyTable 
(
    ID int identity(1,1), 
    RowID char(10), 
    EffectiveDate DateTime, 
    InsertDateTime DateTime 
) 

INSERT INTO #MyTable(RowID, EffectiveDate, InsertDatetime) VALUES 
('55555', '2017-06-01 00:00:00.000','2017-06-01 13:19:01.000') 
INSERT INTO #MyTable(RowID, EffectiveDate, InsertDatetime) VALUES 
('55555', '2017-07-01 00:00:00.000','2017-06-01 13:34:01.000') 
INSERT INTO #MyTable(RowID, EffectiveDate, InsertDatetime) VALUES 
('55555', '2017-07-01 00:00:00.000','2017-06-01 13:54:01.000') 
INSERT INTO #MyTable(RowID, EffectiveDate, InsertDatetime) VALUES 
('55555', '2017-07-01 00:00:00.000','2017-06-01 13:56:01.000') 

--The correct output it should return 
--SELECT * FROM #MyTAble WHERE ID IN (1,4) order by 4 

;WITH CTE AS 
(
    SELECT ID, RowID, EffectiveDate, InsertDateTime, 
    ROW_Number() OVER (Order by InsertDateTime) AS rn 
    FROM #MyTable 
), 
CTE2 AS 
(
    SELECT datediff(second, mc.EffectiveDate, mp.EffectiveDate) as Sec, mc.*, 
    mp.EffectiveDate as Date2 FROM CTE mc 
    JOIN CTE mp 
    ON mc.rn = mp.rn - 1 
) 
SELECT *, CASE WHEN SEC = 0 THEN 1 
ELSE 0 END AS Valid 
FROM CTE2 

Stack Exchange Fiddle

我如何能解決這個問題有什麼建議?

+1

將在最後一個ID永遠是最新的IsertDateTime?如果是這樣,你可以在查詢中使用UNIQUE和ORDER BY嗎? – cbarg

回答

1

您可以通過添加EffetiveDate由行ID,EFFECTIVEDATE和InsertDateTime DESC到ROW_NUMBER分區和排序簡化查詢

;WITH CTE AS 
(
    SELECT ID, RowID, EffectiveDate, InsertDateTime, 
     ROW_Number() OVER (PARTITION BY RowID, EffectiveDate ORDER BY RowID, EffectiveDate, InsertDatetime DESC) AS rn 
    FROM #MyTable 
) 
SELECT * 
FROM CTE 
WHERE rn = 1 
GO 
 
ID | RowID  | EffectiveDate  | InsertDateTime  | rn 
-: | :--------- | :------------------ | :------------------ | :- 
1 | 55555  | 01/06/2017 00:00:00 | 01/06/2017 13:19:01 | 1 
4 | 55555  | 01/07/2017 00:00:00 | 01/06/2017 13:56:01 | 1 

dbfiddle here

+0

謝謝,這是做到了。 – smr5

+0

我很樂意幫助 – McNets

1

我想你」重新複雜化的事情。只要你分區由RowIDEffectiveDaterow_number電話,以便它通過InsertDatetime並選擇行與rn = 1

;WITH cte AS 
(
    SELECT ID, RowID, EffectiveDate, InsertDateTime, 
    ROW_NUMBER() OVER (PARTITION BY RowID, EffectiveDate ORDER BY InsertDatetime DESC) AS rn 
    FROM #MyTable 
) 
SELECT ID, RowID, EffectiveDate, InsertDateTime 
FROM cte 
WHERE rn = 1 

Stack Exchange Fiddle

+0

謝謝,它工作。 – smr5

相關問題