Use of GROUP BY twice in MySQL

前端 未结 5 1408
情话喂你
情话喂你 2020-12-31 08:43

My table looks like this.

Location    Head    Id  IntTime
1           AMD     1   1
2           INTC    3   3
3           AMD     2   2
4           INTC    4         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 09:22

    If I understand correctly, you want the rows that have the smallest int/time values by head and id. I am not seeing what the second "group by head" is getting you.

    The following does what I think you want:

    select t.*
    from t join
         (select head, id, min(intTime) as min_intTime
          from t
          group by head, id
         ) tsum
         on tsum.head = t.head and
            tsum.id = t.id and
            tsum.min_intTime = t.intTime
    

    You might just want the smallest intTime for all "head" values. If so, the query looks like:

    select t.*
    from t join
         (select head, min(intTime) as min_intTime
          from t
          group by head
         ) tsum
         on tsum.head = t.head and
            tsum.min_intTime = t.intTime
    

提交回复
热议问题