sql分组查询显示所有字段

yiyi_fish 2009-04-09 09:34:34
我sql里有这样的记录:
uname score location remark
-----------------------------------------
mary 30 sh hello
mary 40 sz thanks
kate 24 sd hi
kate 45 uy sorry
moss 28 sh hello
moss 0 sz hi

我现在想查询出一样uname,对应的score是最大的那条记录。
结果是:

uname score location remark
-----------------------------------------
mary 40 sz thanks
kate 45 uy sorry
moss 28 sh hello
所有的字段都要显示出来,怎么查啊?
...全文
819 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ws_hgo 2009-04-09
  • 打赏
  • 举报
回复
人齐结贴
ws_hgo 2009-04-09
  • 打赏
  • 举报
回复
create table #tb(uname varchar(10), score int, location varchar(10) ,    remark varchar(10) )
insert #tb select 'mary',30,'sh','hello'
insert #tb select 'mary',40,'sz','thanks'
insert #tb select 'kate',24,'sd','hi'
insert #tb select 'kate',45,'uy','sorry'
insert #tb select 'moss',28,'sh','hello'
insert #tb select 'moss',0,'sz','hi'
go
select * from #tb a where exists(select 1 from #tb where uname=a.uname and score<a.score)

uname score location remark
---------- ----------- ---------- ----------
mary 40 sz thanks
kate 45 uy sorry
moss 28 sh hello

(3 行受影响)
mugua604 2009-04-09
  • 打赏
  • 举报
回复 1
LS不正确,如果有多个UNAME有相同的SCORE,数据出错!
you_tube 2009-04-09
  • 打赏
  • 举报
回复
用辅助列方法
create table tb(uname varchar(10), score int, location varchar(10) ,    remark varchar(10) )
go

insert tb select 'mary' ,30, 'sh' , 'hello'
insert tb select 'mary', 40, 'sz' , 'thanks'
insert tb select 'kate' ,24, 'sd' , 'hi'
insert tb select 'kate' ,45, 'uy' , 'sorry'
insert tb select 'moss', 28, 'sh' , 'hello'
insert tb select 'moss', 0, 'sz' , 'hi'
go
select * from tb a WHERE score = (SELECT MAX(score) FROM tb WHERE uname = a.uname) ORDER BY uname
go
drop table tb
go
/*
uname score location remark
---------- ----------- ---------- ----------
kate 45 uy sorry
mary 40 sz thanks
moss 28 sh hello*/

sdhdy 2009-04-09
  • 打赏
  • 举报
回复
create table tb(uname varchar(10), score int, location varchar(10) ,    remark varchar(10) )
go

insert tb select 'mary' ,30, 'sh' , 'hello'
insert tb select 'mary', 40, 'sz' , 'thanks'
insert tb select 'kate' ,24, 'sd' , 'hi'
insert tb select 'kate' ,45, 'uy' , 'sorry'
insert tb select 'moss', 28, 'sh' , 'hello'
insert tb select 'moss', 0, 'sz' , 'hi'
go
select * from tb a where not exists(select 1 from tb where uname=a.uname and score>a.score)
go
drop table tb
go
/*
uname score location remark
---------- ----------- ---------- ----------
mary 40 sz thanks
kate 45 uy sorry
moss 28 sh hello

(所影响的行数为 3 行)

*/
yiyi_fish 2009-04-09
  • 打赏
  • 举报
回复
一发贴格式都乱了,我再整理一下

姓名 分数 地址 备注
-----------------------------------------
mary 40 sz thanks
kate 45 uy sorry
moss 28 sh hello
sdhdy 2009-04-09
  • 打赏
  • 举报
回复
select  * from tb a where not exists(select 1 from tb where uname=a.uname and score>a.score)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧