sql取A字段重复记录的B字段值最大的一条记录
假设要查询的表是 A,字段有:id,name,other
select A.id,A.name,A.other
from A inner join
(select max(id) as id from A group by name) as B
on A.id=B.id
以上语句就可以实现。
我给出测试语句你测试一下吧.
--创建表A
create table A
(
id int primary key,
name varchar(20),
other varchar(10)
)
--给表A插入数据
insert into A values(1,'lxy','wang')
insert into A values(2,'lxy','zhang')
insert into A values(3,'lxy','li')
insert into A values(4,'clxy','yang')
insert into A values(5,'ylxy','bai')
--查询所有记录
select * from A
--查询要求的结果
select A.id,A.name,A.other
from A inner join
(select max(id) as id from A group by name) as B
on A.id=B.id
--删除表A
drop table A
测试结果如下图: (如果有需要,你可以加入排序子句对结果进行排序!)
希望对你有帮助!
--如果表中还有其他字段要查出,那么
select * from 表 where id in
(select max(id) from 表 group by name )
from 表名 b,(select max(id) as mid from 表名 group by name) a
where a.mid=b.id;