【问题标题】:Last Updated Item from Table表中最后更新的项目
【发布时间】:2020-09-23 12:03:00
【问题描述】:
UniqueIndex         Item
521                          ABC
520                          ABC
519                          ABC
518                          ABC
517                          CDC
516                          CDC
515                          CDC

结果需要 T-SQL

521               ABC
517              CDC

【问题讨论】:

    标签: sql tsql select group-by greatest-n-per-group


    【解决方案1】:

    对于这个 2 列数据集,您可以只使用聚合:

    select item, max(uniqueIndex) lastUniqueIndex
    from mytable
    group by item
    

    如果您要显示更多列,则可以使用子查询进行过滤:

    select t.*
    from mytable t
    where t.uniqueIndex = (select max(t1.uniqueIndex) from mytable t1 where t1.item = t.item)
    

    对于此处的性能,请考虑在(item, uniqueIndex) 上建立索引。

    你也可以使用窗口函数:

    select *
    from (
        select t.*, row_number() over(partition by item order by uniqueIndex desc) rn
        from mytable t
    ) t
    where rn = 1
    

    【讨论】:

    • 谢谢。对不起,我忘了提到表也有其他列
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多