【问题标题】:Select only the most recent datarows [duplicate]仅选择最近的数据行 [重复]
【发布时间】:2022-01-11 18:58:24
【问题描述】:

我有一个表格,其中包含特定产品的多个条目,您可以创建一个这样的示例:

CREATE TABLE test(
    [coltimestamp] [datetime] NOT NULL,
    [col2] [int] NOT NULL,
    [col3] [int] NULL,
    [col4] [int] NULL,
    [col5] [int] NULL)
GO

Insert Into test 
values ('2021-12-06 12:31:59.000',1,8,5321,1234), 
('2021-12-06 12:31:59.000',7,8,4047,1111),
('2021-12-06 14:38:07.000',7,8,3521,1111),
('2021-12-06 12:31:59.000',10,8,3239,1234),
('2021-12-06 12:31:59.000',27,8,3804,1234),
('2021-12-06 14:38:07.000',27,8,3957,1234)

如果您愿意,您可以将 col2 视为产品编号。 我需要的是对这种返回 col2 唯一数据的表的查询,它必须为非唯一 col2 条目选择最近的时间戳。

换句话说,我需要每个产品的最新条目

因此,在示例中,结果将少显示两行:col2 = 7 和 col2 = 27 的旧时间戳被删除

感谢您的先进知识

【问题讨论】:

  • 这个问题已经被问过很多次了。使用 ROW_NUMBER
  • 据我所知,数据已经有行号

标签: sql-server group-by distinct


【解决方案1】:

为每个 col2 值按时间戳的降序提供行号 ROW_NUMBER()

;with cte as(
  Select  rn=row_number() over(partition by col2 order by coltimestamp desc),*
   From table_name
)
Select * from cte
Whwre rn=1;

【讨论】:

  • 谢谢您,您的方法有效。我还发现了一个有趣的解决方法,即在同一个表的子集上进行连接,如果这也是一个可行的选择,我想知道
猜你喜欢
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 2016-02-27
  • 2019-01-06
  • 2014-09-02
  • 1970-01-01
相关资源
最近更新 更多