2012-04-16 177 views
1

使用SQL Server 2000如何获取最近的日期

我想获得每个id的总数的最大值(日期)。

ID Date Total 

01 02/01/2012 500 
01 01/02/2012 1000 
01 02/03/2012 350 
02 17/01/2012 250 
02 15/02/2012 150 
03 01/12/2011 225 
... 
... 

我想获得每个id的总数(日期)。

尝试查询

Select id, total from table1 where date > max(date) group by id, total 

获取错误消息作为

“聚合不应出现在WHERE子句,除非它是在含有HAVING子句或选择列表在子查询中,并且列被汇总的是外部参考。“

预期输出

ID Date Total 

01 02/03/2012 350 
02 15/02/2012 150 
03 01/12/2011 225 
... 
... 

如何做到这一点。

需要查询帮助

回答

4
Select id, date, total 
from table1 t 
where date = (select max(date) from table1 where id = t.id 
group by id) 
3

这应该为你工作:

select * 
from total t inner join 
    ( select id, max(date) as date 
     from total 
     group by id) m on t.id = m.id and t.date = m.date 
0

这个查询将工作

select * from dbo.Table t1 
where Date >= (select max(Date) from dbo.Table t2 
where t1.ID = t2.ID)