T-SQL select rows by oldest date and unique category

前端 未结 2 1186
無奈伤痛
無奈伤痛 2021-01-07 11:11

I\'m using Microsoft SQL. I have a table that contains information stored by two different categories and a date. For example:

ID   Cat1   Cat2   Date/Time         


        
2条回答
  •  北海茫月
    2021-01-07 11:27

    Quassnoi's answer is fine, but I'm a bit uncomfortable with how it handles dups. It seems to return based on insertion order, but I'm not sure if even that can be guaranteed? (see these two fiddles for an example where the result changes based on insertion order: dup at the end, dup at the beginning)

    Plus, I kinda like staying with old-school SQL when I can, so I would do it this way (see this fiddle for how it handles dups):

    select *
    from my_table t1
      left join my_table t2
        on t1.cat1 = t2.cat1
        and t1.cat2 = t2.cat2
        and t1.datetime > t2.datetime
    where t2.datetime is null
    

提交回复
热议问题