views:

44

answers:

2

I have a log table, each row representing an object logging its state. Each object has a unique, unchanging GUID. There are multiple objects logging their states, so there will be thousands of entries, with objects continually inserting new logs. Everytime an object checks in, it is via an INSERT.

I have the PrimaryKey, GUID, ObjectState, and LogDate columns in tblObjects. I want to select the latest (by datetime) log entry for each unique GUID from tblObjects, in effect a 'snapshot' of all the objects.

How can this be accomplished?

+1  A: 

You could use a subquery to filter for the last log entries:

select t1.*
from tblObjects t1
where t1.LogDate = (
    select max(LogDate) 
    from tblObjects t2
    where t1.guid = t2.guid
)

Or alternatively, using not exists:

select t1.*
from tblObjects t1
where not exists (
    select *
    from tblObjects t2
    where t1.guid = t2.guid
    and t1.LogDate < t2.LogDate
)

Note that the usual approach would be to store a bitflag indicating whether a row is current. That allows you to query faster.

Andomar
I didn't consider the bitflag approach, that seems to be a good preemptive solution. Thanks!
Simpleton
Adding a bitflag will make queries faster but inserts more cumbersome. For every insert an update will be needed to unset the bitflag for the previous "current" row for the particular GUID.
Trey
Yeah, the flag approach seems cumbersome. What about a materialised/indexed view?
Chris Bednarski
Ended up going with your sub queries, worked like a charm. 'Preciete it Andomar
Simpleton
A: 

It sounds like you want to select the most recent LogDate for each individual GUID. Using a "group by" with the max function should do what you need:

Select *, max(LogDate)
From tblObjects
Group By GUID
Trey
ObjectState does not appear in GROUP BY and is not enclosed in an aggregate function. Maybe SQL Server supports this as a language extension and I'm just clueless, but that looks like an error...
Dan LaRocque
This seemed to be the most elegant solution, but I had this problem as well.
Simpleton
I assumed MySQL was being used. This will not work in MS SQL Server for exactly the reason you stated.
Trey