如何查出这样的记录?
这样一个表:
ID name 成绩
-----------------
1 张三 90
2 张三 80
3 李四 80
4 李四 65
5 李四 20
6 张三 30
7 李四 90
8 李四 50
---------------------
不断的有成绩记录添加进来,ID自动增长。
如何得到每个人的最新一条记录?比如上边,我需要得到:
6 张三 30
8 李四 50
谢谢!
[解决办法]
select * from table where id in(select max(id) from table group by name)
[解决办法]
- SQL code
declare @t table ( ID int , name varchar(8),cj float)insert into @tselect 1,'张三',90 union allselect 2,'张三',90 union allselect 3,'李四',80 union allselect 4,'李四',65 union allselect 5,'李四',20 union allselect 6,'张三',30 union allselect 7,'李四',90 union allselect 8,'李四',50 select name,max(ID),replace(max(convert(char(8),id)+convert(varchar(8),cj)), max(convert(char(8),id)),'')from @tgroup by name---------------------------(8 行受影响)name -------- ----------- ----------------------------------------------------------------------------------------------------------------李四 8 50张三 6 30(2 行受影响)
[解决办法]
- SQL code
--楼主还可以这样 declare @t table ( ID int , name varchar(8),cj float)insert into @tselect 1,'张三',90 union allselect 2,'张三',90 union allselect 3,'李四',80 union allselect 4,'李四',65 union allselect 5,'李四',20 union allselect 6,'张三',30 union allselect 7,'李四',90 union allselect 8,'李四',50 ;with t as (select row_number() over ( partition by name order by id desc) as Row ,* from @t )select ID,name,cj from t where Row = 1/×(8 行受影响)ID name cj----------- -------- ----------------------8 李四 506 张三 30(2 行受影响)×/
[解决办法]
- SQL code
--楼主还可以这样 declare @t table ( ID int , name varchar(8),cj float)insert into @tselect 1,'张三',90 union allselect 2,'张三',90 union allselect 3,'李四',80 union allselect 4,'李四',65 union allselect 5,'李四',20 union allselect 6,'张三',30 union allselect 7,'李四',90 union allselect 8,'李四',50 select * from @t t where not exists(select 1 from @t where name=t.name and id>t.id)/×(8 行受影响)ID name cj----------- -------- ----------------------6 张三 308 李四 50(2 行受影响)×/