My table looks like this.
Location Head Id IntTime
1 AMD 1 1
2 INTC 3 3
3 AMD 2 2
4 INTC 4
SELECT a.*
FROM test a
NATURAL JOIN
(
SELECT c.Head, c.Id, MIN(c.IntTime) AS IntTime
FROM test c
NATURAL JOIN
(
SELECT Id, MIN(IntTime) AS IntTime
FROM test
GROUP BY Id
) d
GROUP BY c.Head
) b
ORDER BY a.Location
I am not sure how your sample result arrived at Location = 7 for ARMH, for instance. Try this...
SELECT MIN(Location), Head, Id, MIN(IntTime)
FROM test
GROUP BY Head, Id
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
Use UNION syntax?
(SELECT Location, Head, Id, MIN(IntTime) FROM test
GROUP BY Id)
UNION
(SELECT Location, Head, Id, MIN(IntTime) FROM test2
GROUP BY Head)
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
).