I have the following query:
select vkbr.vkID, vkbr.bid, vkbr.Date, vkbr.agID
FROM camp c (NOLOCK)
JOIN ag (NOLOCK) ON ag.campID = c.id
JOIN vkbr WITH (NOLOCK) ON vkbr.agID = ag.id
where c.id = 648322
order by vkbr.vkID;
Which has the following results:
vkID bid Date agID
1072845175 NULL 2012-12-04 20:20:12.390 16074852
1072845177 0.74 2012-12-01 23:36:11.280 16074852
1072845177 0.18 2012-12-02 23:01:26.123 16074852
1072845177 0.72 2012-12-09 23:38:52.503 16074852
1072845177 0.62 2012-12-14 15:26:49.643 16074852
1072845178 2.91 2012-12-08 19:37:00.877 16074852
1072845178 0.73 2012-12-13 17:54:11.240 16074852
1072845178 2.70 2012-12-14 15:26:49.643 16074852
I need to group by vkID, get the max(Date) and the bid on the max(Date) to get this result:
1072845175 NULL 2012-12-04 20:20:12.390 16074852
1072845177 0.62 2012-12-14 15:26:49.643 16074852
1072845178 2.70 2012-12-14 15:26:49.643 16074852
select vkbr.vkID, MAX(vkbr.Date) as Date, MIN(vkbr.agID) as agID
FROM camp c (NOLOCK)
JOIN ag (NOLOCK) ON ag.campID = c.id
JOIN vkbr WITH (NOLOCK) ON vkbr.agID = ag.id
where c.id=648322
group by vkbr.vkID
having Max(vkbr.Date) is not null
and Max(Date) <= '2012-12-18';
Since I cannot add the bid column in SELECT statement - receive this error: Column 'bid' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
So I tried to do this with temp tables:
create table #getBids (
vkID bigint not null,
Date datetime null,
agID bigint null);
insert into #getBids (vkID, Date, agID)
select vkbr.vkID, MAX(vkbr.Date) as Date, MIN(vkbr.agID) as agID
FROM camp c (NOLOCK)
JOIN ag (NOLOCK) ON ag.campID = c.id
JOIN vkbr WITH (NOLOCK) ON vkbr.agID = ag.id
where c.id = 648322
group by vkbr.vkID
having Max(vkbr.Date) is not null
and Max(Date) <= '2012-12-18';
Now this gives me the result I want:
select vkbr.vkID, vkbr.bid from vkbr
inner join #getBids on vkbr.Date = #getBids.Date
and vkbr.agID = #getBids.agID
and vkbr.vkID = #getBids.vkID
I was wondering is there anyway to accomplish the same result in one query w/o creating the temp table? Any help is greatly appreciated.