我想知道是否有更好的方法从 c1 列获取最大值,然后从 c2 列获取选定行的最大值,而不是
SELECT MAX(c1) , MAX(c2) FROM t GROUP BY c1 HAVING c1 = MAX(c1)
我想知道是否有更好的方法从 c1 列获取最大值,然后从 c2 列获取选定行的最大值,而不是
SELECT MAX(c1) , MAX(c2) FROM t GROUP BY c1 HAVING c1 = MAX(c1)
SELECT Max(t2.c1) as C1,
Max(t1.c2) as C2
FROM t t1
INNER JOIN (SELECT Max(c1) AS C1
FROM t) t2
ON t1.c1 = t2.c1
只需阅读您对 hkutluay 回复的评论,这可能就是您想要的:
select MAX(colName)
from
(select col1 as colName
from tableName
union
select col2
from tableName) subqueryName
我不太确定你是想要所有不同的 c1 还是只想要最大值。
如果你想要所有 c1:
SELECT c1, MAX(c2) FROM t GROUP BY c1;
如果您只想要最大 c1:
SELECT c1, c2 FROM t ORDER BY c1 DESC, c2 DESC LIMIT 1;
我知道mysql没有CTE;但是因为问题也被标记为 SQL,并且 CTE 是子查询的合理干净解决方案,所以为了完整起见,这里是 CTE 版本:
WITH zmax AS (
SELECT MAX(v1) AS v1
FROM ztable
)
SELECT zt.v1
, MAX(zt.v2) AS v2
FROM ztable zt
JOIN zmax mx ON zt.v1 = mx.v1
GROUP BY zt.v1
;