I have this Query:
SELECT p.ProductName,
dt.MaxTimeStamp,
p.Responsible
FROM Product p
LEFT JOIN (SELECT ProductID, MAX(TimeStamp) AS MaxTimeStamp
FROM StateLog
WHERE State = 0
GROUP BY ProductID, State) dt ON p.ProductID = dt.ProductID
ORDER BY p.ProductName;
It works like it should, but now I need to SELECT “State” out too.
The tricky part is, that I only want the lastest “TimeStamp” where “State” was false.
But now I also need the “State” for the lastest “TimeStamp”.
I tried this:
SELECT p.ProductName, dt.State, dt.MaxTimeStamp, p.Responsible
FROM Product p
LEFT JOIN (SELECT ProductID, MAX(TimeStamp) AS MaxTimeStamp, State
FROM StateLog
WHERE State = 0
GROUP BY ProductID, State) dt ON p.ProductID =dt.ProductID
ORDER BY p.ProductName;
But it didn’t work, because it gave me the “State” for the lastest “TimeStamp”.
So I hope there is some clever heads out there that can help me. I’m guessing that this is either very simple or very hard to solve.
Struggling to decipher what you’re looking for but reading between the lines could it be summarised as:
1) Most recent StateLog.Timestamp where State is zero
2) State of most recent StateLog.Timestamp
In which case, the following (rather ugly) query would probably work. Assumed the ‘Status’ column in your group by was a misprint of ‘State’ as its not returned anywhere.