how to add column in SQL Query that incl. LEFT OUTER JOIN

Posted by radbyx on Stack Overflow See other posts from Stack Overflow or by radbyx
Published on 2010-05-27T00:24:34Z Indexed on 2010/05/27 0:31 UTC
Read the original article Hit count: 235

Filed under:

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.

© Stack Overflow or respective owner

Related posts about sql