【问题标题】:Grab the latest record if effectivedate is the same with other rows如果有效日期与其他行相同,则获取最新记录
【发布时间】:2017-11-03 05:06:46
【问题描述】:

我正在尝试获取指定 RowID 的所有行,其中 EffectiveDate 不同。 但是,如果我们有多行具有相同的EffectiveDate,我想抓取所有其他行和使用InsertDateTime 列插入的最后一条记录,用于相同的日期。

这里是示例数据:

所以在这个例子中,我正在寻找的输出是这样的:

我们将跳过 ID 为 2 && 3 的行,因为它们的 InsertDateTime 小于行 ID 4 的 InsertDateTime

我采取的方法是在EffectiveDatesecond 之间做一个datediff,如果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

关于如何解决此问题的任何建议?

【问题讨论】:

  • 最后一个 ID 是否总是最新的 IsertDateTime?如果是这样,您可以在查询中使用 UNIQUE 和 ORDER BY 吗?

标签: sql select sql-server-2012


【解决方案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 |生效日期 |插入日期时间 | rn -: | :--------- | :----------------- | :----------------- | :- 1 | 55555 | 01/06/2017 00:00:00 | 2017 年 1 月 6 日 13:19:01 | 1 4 | 55555 | 01/07/2017 00:00:00 | 2017 年 1 月 6 日 13:56:01 | 1

dbfiddle here

【讨论】:

  • 很高兴为您提供帮助
【解决方案2】:

我认为你把事情复杂化了。只需将您的row_number 调用按RowIDEffectiveDate 划分,按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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多