SQL Query: List the last weightings of individual files, grouped by file name
I need help with the following SQL command.
I have 2 tables:
Weights table with columns:
- WeighingId
- FILEID
- MyDateTime
Table files with columns:
- FILEID
- name
Weighing tables contain information when the specified file was weighed. I need to make a list of the last weightings of individual files, grouped by file name. The final table will contain Weighing.Id, the file name (File.Name) and the second column when this file was last weighed MAX (Weighings.MyDateTime).
There may be duplicate filenames with different File.Id, and I need to group all files with the same name (so I cannot group by File.FileId).
I tried to use this code but it doesn't work:
SELECT W.WeighingId AS WeighingId, MAX(W.MyDateTime) AS MaxMyDateTime
FROM Files F INNER JOIN Weighings W ON W.FileId = F.FileId
GROUP BY F.Name
ORDER BY F.Name
source to share
It should be like:
SELECT
F.Name,
(SELECT TOP 1 WeighingId FROM Weighings WHERE MyDateTime = MAX(W.MyDateTime)),
MAX(W.MyDateTime) AS MaxMyDateTime
FROM Files F
INNER JOIN Weighings W ON W.FileId = F.FileId
GROUP BY F.Name
ORDER BY F.Name
You don't need F.Name to be in the select list (the opposite is not valid, as in the WeighingId in your example). I think the problem was how you could combine the WeighingId for the selection.
source to share