简体   繁体   English

MySQL-查询帮助选择按日期分组的最新时间戳结果

[英]MySQL - query help select results with latest timestamp grouped by date

I have a table containing the following fields: date, time, node, result describing some numeric result for different nodes at different dates and times throughout each day. 我有一个包含以下字段的表:日期,时间,节点,结果,描述了每天不同日期和时间不同节点的一些数值结果。 Typical listing will look something like this: 典型的清单如下所示:

date       | time  | node | result
----------------------------------
2011-03-01 | 10:02 | A    | 10
2011-03-01 | 11:02 | A    | 20
2011-03-02 | 03:13 | A    | 23
2011-03-02 | 12:15 | A    | 18
2011-03-02 | 13:15 | A    | 8
2011-03-01 | 13:12 | B    | 2
2011-03-01 | 14:26 | B    | 1
2011-03-02 | 08:00 | B    | 6
2011-03-02 | 07:22 | B    | 3
2011-03-02 | 21:19 | B    | 4

I want to form a query that'll get the last result from each day for each node, such that I'd get something like this: 我想形成一个查询,该查询将从每个节点的每一天中获取最后的结果,这样我将得到如下信息:

date       | time  | node | latest
-----------------------------------
2011-03-01 | 11:02 | A    | 20
2011-03-01 | 14:26 | B    | 1
2011-03-02 | 13:15 | A    | 8
2011-03-02 | 21:19 | B    | 4

I thought about doing a group by date, node , but then extracting the last value was a mess (I used group_concat( result order by time ) and used SUBSTRING() to get the last value. Baah, I know). 我考虑过group by date, node进行group by date, node ,但是提取最后一个值是一团糟(我使用group_concat( result order by time )并使用SUBSTRING()获得了最后一个值。Baah,我知道)。 Is there a simple way to do this in mysql? 在mysql中有一种简单的方法吗?

I'm pretty sure I saw a similar request solving it very nice without using an INNER JOIN but I can't find it right now (and it might have been SQL Server) but following should work nevertheless. 我很确定我看到了一个类似的请求,即使不使用INNER JOIN也能很好地解决它,但是我现在无法找到它(它可能是SQL Server),但是下面的命令仍然可以工作。

SELECT n.*
FROM   Nodes n
       INNER JOIN (
         SELECT MAX(time) AS Time
                , Date
                , Node
         FROM   Nodes
         GROUP BY
                Date
                , Node
       ) nm ON nm.time = n.time
               AND nm.Date = n.Date
               AND nm.Node = n.Node

I would think that you would have to use something like the Max() function. 我认为您将不得不使用诸如Max()函数之类的东西。 Sorry I don't have mysql, so I can't test but I would think something like this 抱歉,我没有mysql,所以我无法测试,但我会认为是这样

select t.date, t.node, t.latest, Max(time) from Table t Group By t.node, t.date

I think the aggregate function will return only the one row per grouping. 我认为聚合函数每个分组将仅返回一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM