我正在尝试为每个唯一的galaxyId列值检索最大的stellarMass属性。让我分解一下。
首先,以下查询返回列表中关联对象的ID和stellarMass,我对列表中的每个DES.galaxyId感兴趣。
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
这将返回表格
的表格-------------------------------------------------
| descID | progID | progStellarMass |
-------------------------------------------------
| 0 | 34 | 8.3345 |
| 0 | 38 | 18.3345 |
| 2 | 198 | 80.3345 |
| 5 | 99 | 6.3345 |
| 5 | 8 | 3.3345 |
-------------------------------------------------
因此对于(0,2,5 ...)中的每个DES.galaxyId / descID,可以返回多个结果。 我想要做的是,从这个结果中,为每个唯一的descID选择max(progStellarMass)的结果。我需要在一个查询中执行此操作。
所以,我想要的将返回下表:
----------------------------------------------------
| descID | progID | MAXprogStellarMass |
----------------------------------------------------
| 0 | 38 | 18.3345 |
| 2 | 198 | 80.3345 |
| 5 | 99 | 6.3345 |
----------------------------------------------------
非常感谢任何帮助。我打开一个新问题的原因是因为我首先运行这个额外的查询来获取我需要处理的数据表。
答案 0 :(得分:1)
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
答案 1 :(得分:0)
我有一个可能不是最好的解决方案,但至少它应该有效(没有实际运行它)。使用子查询时要小心,请仔细检查说明。
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
提示:有一种方法可以强迫"子查询始终在主查询之前运行。它是通过使用额外的select * from()
包围子查询来完成的select a,b from (select * from (select a,b from table1 where requirement = "matched") as t1) as t2) where a > b;