【问题标题】:get max ID row from individual rows in sql server从 sql server 中的各个行获取最大 ID 行
【发布时间】:2020-09-15 18:43:03
【问题描述】:

我有如下数据,其中多行具有相同的数据,可以通过 ID 识别。

我需要如下数据。仅获取每组重复记录的单个最大 ID 值,可以通过获取单个最大 ID 来完成

你能帮我解决这个问题吗?

【问题讨论】:

    标签: sql sql-server where-clause greatest-n-per-group


    【解决方案1】:

    您可以使用子查询进行过滤。假设您的表的列名为iddatecol,则为:

    select t.*
    from mytable t
    where t.col = (select max(t1.col) from mytable t1 where t1.id = t.id)
    

    为提高性能,请考虑在(id, col) 上建立索引。

    【讨论】:

      【解决方案2】:

      一种有效的方法——使用正确的索引——是相关子查询:

      select t.*
      from t
      where t.individual = (select max(t2.individual) from t t2 where t2.id = t.id);
      

      正确的索引在(id, individual)

      【讨论】:

        【解决方案3】:

        这应该对你有帮助

        
        create table #sample (type char(1), date datetime, Id bigint)
        insert into #sample values('A', '5/22/2019 4:33', 1065621)
        insert into #sample values('A', '5/22/2019 4:33', 1065181)
        insert into #sample values('A', '5/22/2019 4:33', 1064212)
        insert into #sample values('B', '11/7/2017 1:07', 540180)
        insert into #sample values('B', '11/7/2017 1:07', 540179)
        insert into #sample values('B', '11/7/2017 1:07', 540177)
        
        select * from #sample
        
        select [type], [date], max(id)
        from #sample
        group by [type], [date]
        
        select distinct [type], [date], max(id) over(partition by  [type], [date] )
        from #sample
        
        Drop table #sample
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-27
          • 1970-01-01
          • 2013-12-09
          • 2019-03-09
          相关资源
          最近更新 更多