我尝试抓取RowID
不同的指定EffectiveDate
的所有行。
但是,如果我们有多个具有相同EffectiveDate
的行,我想抓取所有其他行以及使用InsertDateTime
列插入的最后一条记录,以获取相同的日期。
以下是示例数据:
所以在这个例子中,我正在寻找的输出是:
我们正在使用ID' s&& 3,因为他们的InsertDateTime
小于行ID 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
有关如何解决此问题的任何建议?
答案 0 :(得分:1)
您可以通过将EffetiveDate添加到ROW_NUMBER分区并按RowID,EffectiveDate和InsertDateTime DESC排序来简化查询
;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
答案 1 :(得分:1)
我认为你过度复杂化了。只需按row_number
和RowID
分割EffectiveDate
来电,按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 强>