Reputation: 215
I'm attempting to retrieve the maximum stellarMass property for each unique galaxyId column value. Let me break it down.
Firstly, the following query returns a list of associated objects' IDs and stellarMass that I'm interested in for each of the DES.galaxyId's in the list.
SELECT DES.galaxyId as descID,
PROG.galaxyId as progID,
PROG.stellarMass as progStellarMass
FROM Guo2010a..mMR PROG, Guo2010a..mMR DES
WHERE DES.galaxyId in (0,2,5)
AND PROG.galaxyId BETWEEN DES.galaxyId AND DES.lastprogenitorId
AND PROG.snapnum = 48
This returns a table of the form
-------------------------------------------------
| descID | progID | progStellarMass |
-------------------------------------------------
| 0 | 34 | 8.3345 |
| 0 | 38 | 18.3345 |
| 2 | 198 | 80.3345 |
| 5 | 99 | 6.3345 |
| 5 | 8 | 3.3345 |
-------------------------------------------------
So for each DES.galaxyId/descID in (0,2,5...), multiple results can be returned. What I want to do is, from this result, select the result with the max(progStellarMass) for each unique descID. And I need to do this in a single query.
So, what I'm wanting would return the following table:
----------------------------------------------------
| descID | progID | MAXprogStellarMass |
----------------------------------------------------
| 0 | 38 | 18.3345 |
| 2 | 198 | 80.3345 |
| 5 | 99 | 6.3345 |
----------------------------------------------------
Any help would be greatly appreciated. The reason I'm opening a new question is because of this extra query I run first to get the table of data I need to work on.
Upvotes: 0
Views: 85
Reputation: 57
SELECT descID,progID,progStellarMass
FROM
(
SELECT RANK() OVER (PARTITION BY DES.galaxyId ORDER BY PROG.stellarMass DESC) AS RankID, DES.galaxyId as descID,
PROG.galaxyId as progID,
PROG.stellarMass as progStellarMass
FROM Guo2010a..mMR PROG, Guo2010a..mMR DES
WHERE DES.galaxyId in (0,2,5)
AND PROG.galaxyId BETWEEN DES.galaxyId AND DES.lastprogenitorId
AND PROG.snapnum = 48
) AS WRAP
WHERE RankID = 1
Upvotes: 1
Reputation: 1556
I have a solution that might not be the best but at least it should works(didn't actually ran it). Be careful as it uses sub-query, check the explain carefully.
SELECT t1.descID, PROG.galaxyId as progID, MAXprogStellarMass
FROM Guo2010a..mMR PROG, Guo2010a..mMR DES
INNER JOIN
(SELECT DES.galaxyId as descID,
max(PROG.stellarMass) as MAXprogStellarMass
FROM Guo2010a..mMR PROG, Guo2010a..mMR DES
WHERE DES.galaxyId in (0,2,5)
AND PROG.galaxyId BETWEEN DES.galaxyId AND DES.lastprogenitorId
AND PROG.snapnum = 48
GROUP BY DES.galaxyId ) as t1
ON (t1.descID = DES.galaxyId)
WHERE MAXprogStellarMass = PROG.stellarMass
Tips : there is a way to "force" subquery to always runs before the main query. It is done by surrounding the subquery with an extra select * from( )
select a,b from (select * from (select a,b from table1 where requirement = "matched") as t1) as t2) where a > b;
Upvotes: 0