[英]Retrieving Maximum Of One Column For Each Unique Value From Another
我尝试过的并且返回错误数据的内容:
SELECT type, pid, MAX(distance) FROM table GROUP BY type
这将检索每一个独特的type
和正确的对应的最大distance
为每个type
从我的数据库(总共有26个不同的独特的type
值,这将永远不会改变),但pid
值是不正确的。 如何检索正确和对应的pid
值?
表格数据示例:
pid | type | distance | ...
675 | dcj | 273060192 | ...
743 | mcj | 273046176 | ...
284 | dcj | 271592224 | ...
4091 | lj | 255217488 | ...
743 | lj | 255170160 | ...
4091 | lj | 230840928 | ...
应该返回什么:
pid | type | distance
675 | dcj | 273060192
743 | mcj | 273046176
4091 | lj | 255217488
有关数据一些值得注意的信息:有每多个条目pid
值,并有可能成为每多个条目pid
值具有相同type
的值。
我是否需要利用PHP运行两个不同的查询,其中第一个通过GROUP BY type
获取26个不同type
值,第二个查询执行26次不同的时间(每个唯一type
值一次),并通过某种方式找到每种type
的最大值例如WHERE type="' . $type . '" ORDER BY distance DESC LIMIT 1
? 还是可以在一个SQL查询中完成?
该查询给出所需的结果。
SELECT t.type, t.pid, t.distance
FROM table t
INNER JOIN (SELECT type, MAX(distance) as distance FROM table GROUP BY type) as m
ON t.type = m.type and t.distance = m.distance
ORDER BY t.type
对于两个或更多个pid具有相同最大距离的情况(不太可能),它将返回所有具有相同最大距离的pid。
您可以执行GROUP BY
查询,他们将其连接到原始表以获取正确的pid
,如下所示:
SELECT x.type, t.pid, x.max_dist
FROM (
SELECT type, MAX(distance) as max_dist FROM table GROUP BY type
) as x
JOIN table t ON x.max_dist=t.distance AND x.type=t.type
使用公用表表达式也可以做到这一点:
;
WITH cte
AS ( SELECT pid,
type,
distance,
ROW_NUMBER() OVER ( PARTITION BY pid ORDER BY distance DESC ) AS RowNum
FROM table_name
)
SELECT pid,
type,
distance
FROM cte
WHERE RowNum = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.