MySQL Select Group of Records Based on latest timestamp

后端 未结 2 528
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 13:09

I have a routine that runs every few hours that creates several entries in a table used for logging. What I need to do is select all the records with the most recent

相关标签:
2条回答
  • 2021-01-19 14:08

    Assuming you mean multiple entries in your Table_Logs table could have the same timestamp and you want to return each of those that were entered most recently, you need to use GROUP BY:

    SELECT Field1, Field2, Max(TimeStamp) maxTime
    FROM Table_Logs
    WHERE Account_Id = '12345'
    GROUP BY Field1, Field2
    

    Field1, etc. are the fields you want to return in Table_Logs.

    Here is some sample SQL Fiddle to try out.

    Good luck.

    0 讨论(0)
  • 2021-01-19 14:09

    I think what you want is to group by the timestamp. Assuming that all the ones entered at 10am had the same timestamp, and 2 pm, ditto, would be something like:

      SELECT timestamp, Field1, Field2
        FROM Table_Logs
    GROUP BY timestamp
    

    If your timestamps are too precise, simply do a substring:

      SELECT LEFT(timestamp, 5), Field1, Field2
        FROM Table_Logs
    GROUP BY LEFT(timestamp, 5)
    

    Assuming the timestamp is a string (log file). If not, you have to stringify it.

    0 讨论(0)
提交回复
热议问题