我試圖抓取指定的所有行RowID
,其中EffectiveDate
與此不同。 但是,如果我們有多行使用相同的EffectiveDate
,我想抓取所有其他行,並使用InsertDateTime
列插入的最後一條記錄的日期相同。如果effectivedate與其他行相同,則獲取最新記錄
這裏是樣本數據:在這個例子中
所以,我在找的輸出是這樣的:
我們跳過與ID的行2 & & 3因爲它們的InsertDateTime
小於第4行的InsertDateTime
。
我採取的方法是做一個datediff
EffectiveDate
之間,如果second
是0
比他們是相同的值,我應該抓住最後一個記錄。但是,使用這種方法,由於我的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
我如何能解決這個問題有什麼建議?
將在最後一個ID永遠是最新的IsertDateTime?如果是這樣,你可以在查詢中使用UNIQUE和ORDER BY嗎? – cbarg