我有以下查询:
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;
结果如下:
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
我需要按 vkID 分组,获取 max(Date) 和 max(Date) 的出价以获得此结果:
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';
由于我无法在 SELECT 语句中添加出价列 - 收到此错误:选择列表中的“出价”列无效,因为它不包含在聚合函数或 GROUP BY 子句中。
所以我尝试用临时表来做到这一点:
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
我想知道是否可以在一个查询中完成相同的结果而无需创建临时表?任何帮助是极大的赞赏。