How do you group by one column and retrieve a row with the minimum value of another column in T/SQL?

前端 未结 6 2063
终归单人心
终归单人心 2021-01-02 00:55

So I know this is a pretty dumb question, however (as the rather lengthily title says) I would like to know how do the following:

I have a table like this:



        
6条回答
  •  清歌不尽
    2021-01-02 01:07

    My understanding is that you can't really do this in one go.

    select Foo, min(Bar) from table group by Foo
    

    ,, gets you the minimum Bar for each distinct Foo. But you can't tie that minimum to a particular ID, because there could be more than one row with that Bar value.

    What you can do is something like this:

    select * from Table t
    join (
       select Foo, min(Bar) as minbar
       from Table group by Foo
    ) tt on t.Foo=tt.Foo and t.Bar=tt.minbar
    

    Note that if there is more than one row with the minimum Bar value, you'll get them all with the above query.

    Now, I am not claiming to be a SQL guru, and it is late where I am, and I may be missing something, but there's my $0.02 :)

提交回复
热议问题