UPDATED
I have the following data in my database, I would like to retrieve data in highlight red border (to get the latest maintenance data of each equipment).
Data:
(I have updated the picture)
How should I construct the query?
UPDATED
I have the following data in my database, I would like to retrieve data in highlight red border (to get the latest maintenance data of each equipment).
Data:
(I have updated the picture)
How should I construct the query?
Something simple like that?
select name, max(maintenance_time)
from table
group by name
Edited Answer:
This query below should work. Do update table name before running the query.
SELECT [Equipment], [Type], MAX(CONVERT(datetime, [MaintenanceTime], 131)) AS [Most_Recent_Maintenance]
FROM [TABLE_NAME]
GROUP BY [Equipment], [Type]
The additional bit of code I added was around datetime conversion of your MaintenanceTime
column. SQL only does MIN/MAX
filtering commands accurately when it's the right data type.
Based on what I see in your table, there's a potential it may not be (See link). I added an additional query to the fiddle for you to see the conversion.
Old Answer:
Based on the picture provided, it seems like each set of maintenance data is posted in 'batches'. Assuming the batch data is all posted using the same date/time, you can use the following query to obtain all records on the latest posting date:
SELECT *
FROM [INSERT_TABLE_NAME]
WHERE DAY([Maintenance Time]) = (SELECT DAY(MAX([Maintenance Time])) FROM [INSERT_TABLE_NAME])
Or if your equipment is not always maintained together in the same batch timings, here's a query to figure out the most recent time each piece of equipment was maintained:
SELECT [Name], [Type], MAX([Maintenance Time]) AS [Most_Recent_Maintenance]
FROM [INSERT_TABLE_NAME]
GROUP BY [Name], [Type]
Be sure to update [INSERT_TABLE_NAME]
to reflect your table naming. I've also created a fiddle for you to view what the query (with your dataset) will look like.
It appears that all your desired data arrives at the same time:
select *
from T
where maintenance_time = (select max(maintenance_time) from T);