新手请教:如果某字段记录相同,怎样根据日期查询最后一条记录?
如果编号相同则选日期最大的记录如下:
编号 日期 字段1 字段2 ...
1000 2007-01-01 1 a ...
0099 2007-02-03 2 b ...
1000 2007-02-08 2 c ...
1001 2007-02-02 0 c ...
0099 2007-03-18 0 l ...
... ... . . ...
得到:
编号 日期 字段1 字段2 ...
0099 2007-03-18 0 l ...
1000 2007-02-08 2 c ...
1001 2007-02-02 0 c ...
------解决方案--------------------select * from 表 a where not exists (select 1 from 表 编号=a.编号 and 日期> a.日期 )
------解决方案----------------------方法一:
Select A.* From TableName A Where 日期 = (Select Max(日期) From TableName Where 编号 = A.编号)
Order By A.编号
--方法二:
Select A.* From TableName A Where Not Exists (Select 日期 From TableName Where 编号 = A.编号 And 日期 > A.日期)
Order By A.编号
--方法三:
Select A.* From TableName A Inner Join (Select 编号, Max(日期) As 日期 From TableName Group By 编号) B
On A.编号 = B.编号 And A.日期 = B.日期
Order By A.编号
------解决方案--------------------create table tt(id varchar(20),
dt datetime,
col1 varchar(20),
col2 varchar(20))
insert into tt select '1000 ', '2007-01-01 ', '1 ', 'a '
union all select '0099 ', '2007-02-03 ', '2 ', 'b '
union all select '1000 ', '2007-02-08 ', '2 ', 'c '
union all select '1001 ', '2007-02-02 ', '0 ', 'c '
union all select '0099 ', '2007-03-18 ', '0 ', '1 '
--select * from tt
select id
,dt
,col1
,col2
from tt a
where dt = ( select top 1 dt
from tt b
where b.id = a.id
order by b.dt desc
)
order by id