T-SQL select rows by oldest date and unique category

前端 未结 2 1187
無奈伤痛
無奈伤痛 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
    
    0 讨论(0)
  • 2021-01-07 11:37

    Have a look at row_number() on MSDN.

    SELECT  *
    FROM    (
            SELECT  *,
                    ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY date_time, id) rn
            FROM    mytable
            ) q
    WHERE   rn = 1
    

    (run the code on SQL Fiddle)

    0 讨论(0)
提交回复
热议问题