2012-04-16 110 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)