sqlsql-serversql-server-2005

SQL Query to get latest price


I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.

ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL

I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?

SELECT * 
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
  AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime) 

UPDATE: In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier.


Solution

  • I think the only solution with your table structure is to work with a subquery:

    SELECT *
       FROM Thing
       WHERE ID IN (SELECT max(ID) FROM Thing 
                       WHERE ThingID IN (1,2,3,4)
                       GROUP BY ThingID)
    

    (Given the highest ID also means the newest price)

    However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to...

    SELECT *
       FROM Thing
       WHERE ThingID IN (1,2,3,4)
         AND IsCurrent = 1
    

    UPDATE

    Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex.

    SELECT T.* 
       FROM Thing T
       JOIN (SELECT ThingID, max(PriceDateTime)
                WHERE ThingID IN (1,2,3,4)
                GROUP BY ThingID) X ON X.ThingID = T.ThingID 
                                    AND X.PriceDateTime = T.PriceDateTime
       WHERE ThingID IN (1,2,3,4)
    

    I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small).

    (I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.)