[英]Only Return Highest Value for another unique Column
Preferably without downloading the entire database and scanning each item, is there a MySQL query that could access this table: 最好不下载整个数据库并扫描每个项目,是否有可以访问此表的MySQL查询:
__________________________________
| ColID | Timestamp |
|___________|_____________________|
|_____2_____|_2012-08-01_12:00:00_|
|_____1_____|_2012-08-01_12:01:00_|
|_____3_____|_2012-08-01_12:02:00_|
|_____3_____|_2012-08-01_12:03:00_|
|_____2_____|_2012-08-01_12:04:00_|
|_____3_____|_2012-08-01_12:05:00_|
And return only these rows: 并只返回这些行:
__________________________________
| ColID | Timestamp |
|___________|_____________________|
|_____1_____|_2012-08-01_12:01:00_|
|_____2_____|_2012-08-01_12:04:00_|
|_____3_____|_2012-08-01_12:05:00_|
So as to extract only one of each ColID
with the highest Timestamp
因此,只提取具有最高
Timestamp
的每个ColID
一个
Use GROUP BY
with MAX
: 使用
GROUP BY
和MAX
:
SELECT ColID, MAX(Timestamp) AS Timestamp
FROM tbl
GROUP BY ColID
Also, just a tip you may want to keep in mind for the future: if you wanted to also select other columns that might be in the same table for each maximum ColID
, you cannot select it directly in the above query due to the nature of GROUP BY
. 此外,您可能还需要记住未来的提示:如果您还想为每个最大
ColID
选择可能位于同一个表中的其他列,则由于其性质,您无法在上述查询中直接选择它。 GROUP BY
。 You will need to wrap the query in a joined subselect joining on both the id and date columns: 您需要将查询包装在连接的subselect中,同时加入id和date列:
SELECT b.*
FROM tbl a
JOIN (
SELECT ColID, MAX(Timestamp) AS max_timestamp
FROM tbl
GROUP BY ColID
) b ON a.ColID = b.ColID AND a.max_timestamp = b.Timestamp
yes you can achive this by using GROUP BY
with MAX
as: 是的,你可以通过使用带有
MAX
GROUP BY
来实现这个目的:
SELECT ColID, MAX(Timestamp) AS max_Timestamp
FROM my_table
GROUP BY ColID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.