Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 get top distinct records

Author  Topic 

tpiazza55
Posting Yak Master

162 Posts

Posted - 2008-01-31 : 14:24:52
hi I am trying to write a query that will return the most recent status of an event

my query is below

SELECT DISTINCT eventname, MIN(Status) AS Expr1, MIN(RecordUpdated) AS Expr2
FROM EventQueue
GROUP BY AuditName

does this query always result with the most recent distinct eventname record?

I need to make sure that the recordupdated is the most recent for the eventname

hey001us
Posting Yak Master

185 Posts

Posted - 2008-01-31 : 14:39:44
SELECT eventname, MAX(Status) AS Expr1, MAX(RecordUpdated) AS Expr2
FROM EventQueue
GROUP BY eventname. can you post your DDL if not works. i dont know which is date filed.

hey
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2008-01-31 : 15:09:38
quote:
SELECT eventname, MAX(Status) AS Expr1, MAX(RecordUpdated) AS Expr2

This won't work because you don't want the max(status), you want the status of the max(RecordUpdated)

Here is a few ways:

set nocount on
declare @eventQueue table (eventname varchar(10), status int, recordUpdated datetime)
insert @eventQueue values ('tg', 10, getdate())
insert @eventQueue values ('tg', 9, getdate()+1)
insert @eventQueue values ('tg', 8, getdate()+2)
insert @eventQueue values ('yak', 10, getdate())
insert @eventQueue values ('yak', 9, getdate()+1)
insert @eventQueue values ('yak', 8, getdate()+2);

-------------------------------------------------------------
--2005
with yak (eventName, status, rowNumber) as
(
select eventName
,status
,row_number() over (partition by eventName order by RecordUpdated desc)
from @EventQueue
)
select eventName
,status
from yak
where rownumber = 1
order by eventName

-------------------------------------------------------------
select eventName
,substring(max(convert(char(23), RecordUpdated, 121) + convert(varchar,status)), 24, 10) as status
from @eventqueue
group by eventName
order by eventName

-------------------------------------------------------------
select eventName
,status
from @eventQueue eq
where recordUpdated = (select max(recordUpdated) from @eventQueue where eventname = eq.eventName)
order by eventName

output:

eventName status
---------- -----------
tg 8
yak 8

eventName status
---------- ----------
tg 8
yak 8

eventName status
---------- -----------
tg 8
yak 8


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -