日期:2014-05-18  浏览次数:20325 次

雪地裸求高手指点!group by一个麻烦的应用!
在做数据库的时候遇到一个比较麻烦的问题.我建了一个数据表,这个表有四个字段,分别是ID,F,P,TIME.现在这个数据表是其他设备传进来数据,一共有一百个ID编号.
              ID         F             P         TIME
                1         0.5         0.7       2006-1-23
                2         0.3           0.6     2006-1-25
                ..........................
                1         0.6           0.9     2006-1-24
                2         0.9           1.0     2006-1-26
      数据不停的往数据里传,我现在只想在前台页面显示各个ID最新的数据,我现在用   Group   by   只能把ID按组分开,我还想用order   by   time   显示出最新的数据,也就是最后要的效果是所有ID最新的数据.不知道我说清楚没有?希望各位大侠能相住,小弟在这里有礼了!

------解决方案--------------------

select * from tbName as tmp
where not exists(select 1 from tbName where ID=tmp.ID and Time> tmp.Time)
------解决方案--------------------
declare @t table(ID int,F int,P int,TIME datetime)

insert into @t select 1,1,1, '2001-01-01 ' union all
select 2,1,1, '2001-01-01 ' union all
select 3,1,1, '2001-01-01 ' union all
select 1,1,1, '2001-01-02 ' union all
select 1,1,1, '2001-01-03 ' union all
select 2,1,1, '2001-01-03 ' union all
select 4,1,1, '2001-01-01 '


select *
from @t a
where not exists(
select 1
from @t
where id = a.id and time > a.time )
order by id

/*

ID F P TIME
----------- ----------- ----------- --------------------------
1 1 1 2001-01-03 00:00:00.000
2 1 1 2001-01-03 00:00:00.000
3 1 1 2001-01-01 00:00:00.000
4 1 1 2001-01-01 00:00:00.000

(所影响的行数为 4 行)

*/
------解决方案--------------------
select * from tbName
where time in (select max(time) from tbName group by 分组字段) order by time