Most recent data point?

  • Thread starter Thread starter Michael Bray
  • Start date Start date
M

Michael Bray

I have a table that stores data points for several different data sources.

The general format is:

DECLARE @Data TABLE
(
DataID int,
TimeCollected int,
DataValue decimal(9,9)
)

INSERT @Data VALUES (1, 1000, 0.75)
INSERT @Data VALUES (1, 1001, 0.69)
INSERT @Data VALUES (1, 1002, 0.77)
INSERT @Data VALUES (2, 1000, 0.45)
INSERT @Data VALUES (2, 1001, 0.49)
INSERT @Data VALUES (2, 1002, 0.53)
INSERT @Data VALUES (3, 1000, 0.50)
INSERT @Data VALUES (3, 1001, 0.35)
INSERT @Data VALUES (3, 1002, 0.41)

I want to pull the most recent datapoint for each of the DataIDs. I can do
it like this:

SELECT d.*
FROM @Data d
INNER JOIN
(
SELECT DataID, MAX(TimeCollected) AS MaxTime
FROM @Data
GROUP BY DataID
) dt ON (d.DataID=dt.DataID) AND (d.TimeCollected=dt.MaxTime)

Is there a more efficient way than this? I may have hundreds of different
DataIDs with tens or hundreds of thousands of data points for each DataID.

Thanks!

-mdb
 
Give your TABLE variable a Primary Key IDENTITY column. Then, you can select
Max(PK) from it.
Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top