The Table:
declare @Table table (
id int,
ticketid int,
sponsor int,
dev int,
qa int,
savedate datetime
)
insert into @Table values (1,100,22,0, 0, '2008-10-29 11:17:59.527')
insert into @Table values (2,100,5,0, 0, '2008-10-29 11:00:37.030')
insert into @Table values (3,101,22,0, 0, '2009-10-29 11:10:27.687')
insert into @Table values (5,101,44,0, 0, '2008-10-31 12:07:52.917')
insert into @Table values (6,101,32,0, 0, '2009-06-30 08:16:12.343')
insert into @Table values (7,101,44,0, 0, '2009-10-31 10:12:11.369')
I'm trying to select the top 1 max of savedate where recordid is a certain record, grouped by sponsor.
My progress:
select max(savedate)
from @Table
where ticketid = 101
group by sponsor
Returns
2009-10-29 11:10:27.687
2009-06-30 08:16:12.343
2009-10-31 10:12:11.370
Close, I'm grouped correctly but I want the top 1 most recent date. So I do this:
select top 1 max(savedate)
from @Table
where ticketid = 101
group by sponsor
Returns
2009-10-29 11:10:27.687
Woohoo, got it, time for a break.. wait.. that's not thie most recent date! Let's try to order these by savedate
select top 1 max(savedate)
from @Table
where ticketid = 101
group by sponsor
order by savedate desc
Oh no! The dreaded:
"Column "@Table.savedate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause."
But savedate IS aggregated in the select list! How do I do what I want to do?