Use of GROUP BY twice in MySQL

前端 未结 5 1358
情话喂你
情话喂你 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条回答
  •  -上瘾入骨i
    2020-12-31 09:41

    This query returns the exact final results you're looking for (example):

    SELECT `final`.*
    FROM `tableName` AS `final`
    JOIN (
        SELECT `thead`.`Id`, `Head`, MIN(`intTime`) AS `min_intTime`
        FROM `tableName` AS `thead`
        JOIN (
            SELECT `Id`, MIN(intTime) as min_intTime
            FROM `tableName` AS `tid`
            GROUP BY `Id`
        ) `tid`
        ON `tid`.`Id` = `thead`.`Id`
        AND `tid`.`min_intTime` = `thead`.`intTime`
        GROUP BY `Head`
    ) `thead`
    ON `thead`.`Head` = `final`.`Head`
    AND `thead`.`min_intTime` = `final`.`intTime`
    AND `thead`.`Id` = `final`.`Id`
    

    How it works

    The innermost query groups by Id, and returns the Id and corresponding MIN(intTime). Then, the middle query groups by Head, and returns the Head and corresponding Id and MIN(intTime). The final query returns all rows, after being narrowed down. You can think of the final (outermost) query as a query on a table with only the rows you want, so you can do additional comparisons (e.g. WHERE final.intTime > 3).

提交回复
热议问题