how to add column in SQL Query that incl. LEFT OUTER JOIN
- by radbyx
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, Status) 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, Status) 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.