一个很简单的SQL查询问题,关于分组的,请进来细看,在线等,有答案测试通过即结贴
有如下表
表名 test
fid fdate ftext
1 2007-01-01 a
1 2007-01-02 b
2 2007-01-03 c
2 2007-01-04 d
要求返回如下结果
1 2007-01-02 b
2 2007-01-04 d
就是按FID分组,返回日期最大的记录
但如果不取ftext的值的话,我用
select fid,max(fdate)
from test
group by fid
是可以的,但加上ftext就是四条记录 ,请遇到过类似问题的朋友帮忙看看,多谢
------解决方案--------------------更正
select * from test a
where not exists (
select 1 from test
where fid=a.fid
and fdate> a.fdate
)
法2
select * from test a
where fdate= (
select max(fdate) from test
where fid=a.fid
)
------解决方案----------------------方法一
Select * From test A Where Not Exists(Select fdate From test Where fid = A.fid And fdate > A.fdate)
--方法二
Select * From test A Where fdate = (Select Max(fdate) From test Where fid = A.fid)
--方法三
Select A.* From test A
Inner Join
(Select fid, Max(fdate) As fdate From test Group By fid) B
On A.fid = B.fid And A.fdate = B.fdate
------解决方案--------------------select a.* from test a,(select fid,max(fdate)
from test
group by fid ) b
where a.fid=b.fid and a.fdate=b.fdate