My table looks like this.
Location Head Id IntTime
1 AMD 1 1
2 INTC 3 3
3 AMD 2 2
4 INTC 4
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`
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
).