简体   繁体   中英

Retrieve latest timestamp for each Id in list - MySQL

I'm running a command to retrieve all rows for today with IDs matching 1, 2, 3, etc.

I want to retrieve the latest entry for these IDs for today though.

So rather than getting:

BinID | Timestamp |

2 | 29/04/2021 3:49pm

2 | 29/04/2021 4:41pm

3 | 29/04/2021 2:24pm

I want:

BinID | Timestamp |

2 | 29/04/2021 4:41pm

3 | 29/04/2021 2:24pm

Is this possible?

This is the command I'm running at the moment.

MySqlCommand mysqlcom = new MySqlCommand("SELECT * FROM realtime_gpses WHERE BinId IN (" + binIdsCSVString + ") AND Timestamp >= CURDATE() AND Timestamp < CURDATE() + INTERVAL 1 DAY", mysqlcon);

where binIdsCSVString in this cases is just 2, 3.

You can try this

Select binid, max(timestamp) from table where ... Group by binid

As an alternative to in (1, 2...) you can generate:

where (binid = @binid1 or binid=@binid2.....)

You then add the parameters accordingly. All of this can be generated dynamically, yet it is parameterized.

See SQL select only rows with max value on a column to get row with max value.

and maybe even better: Retrieving the last record in each group - MySQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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