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

前端 未结 6 2035
终归单人心
终归单人心 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:13

    This might help:

    DECLARE @Table TABLE(
            ID INT,
            Foo FLOAT,
            Bar FLOAT,
            Blah FLOAT
    )
    
    INSERT INTO @Table (ID,Foo,Bar,Blah) SELECT 1, 10 ,20 ,30
    INSERT INTO @Table (ID,Foo,Bar,Blah) SELECT 2, 10 ,5 ,1
    INSERT INTO @Table (ID,Foo,Bar,Blah) SELECT 3, 20 ,50 ,40
    INSERT INTO @Table (ID,Foo,Bar,Blah) SELECT 4, 20 ,75 ,12
    
    SELECT  t.*
    FROM    @Table t INNER JOIN
            (
                SELECT  Foo,
                        MIN(Bar) MINBar
                FROM    @Table
                GROUP BY Foo
            ) Mins ON t.Foo = Mins.Foo
                    AND t.Bar = Mins.MINBar
    

提交回复
热议问题