2017-06-01 44 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

相关问题