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

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

    Another option would be something along the lines of the following:

    DECLARE @TEST TABLE(    ID int,    Foo int,    Bar int,    Blagh int)
    INSERT INTO @TEST VALUES (1,10,20,30)
    INSERT INTO @TEST VALUES (2,10,5,1)
    INSERT INTO @TEST VALUES (3,20,50,70)
    INSERT INTO @TEST VALUES (4,20,75,12)
    
    SELECT Id, Foo, Bar, Blagh 
    FROM (
          SELECT id, Foo, Bar, Blagh, CASE WHEN (Min(Bar) OVER(PARTITION BY FOO) = Bar) THEN 1 ELSE 0 END as MyRow
          FROM @TEST) t
    WHERE MyRow = 1
    

    Although this still requires a sub-query it does eliminate the need for joins.

    Just another option.

提交回复
热议问题