如此条件的查询,其SQL语句该怎样写

flyerlxg 2003-11-12 08:26:10
有以下三个字段f1、f2、f3,内容如下
f1 f2 f3
A 7 230
A 8 460
A 9 580
B 7 258
B 8 468
C 7 563
C 9 587
现在要得到以下结果
f1 f2 f3
A 9 580
B 8 468
C 9 587
即按照f1进行分组,组内取f2最大的那条记录。此语句怎样写,请大家帮帮忙忙,我想直接用SQL搞定。
谢谢!
...全文
38 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
flyerlxg 2003-11-12
  • 打赏
  • 举报
回复
谢谢啦!搞定了。
zjcxc 元老 2003-11-12
  • 打赏
  • 举报
回复
--数据测试

--数据测试环境
declare @t table(f1 varchar(1),f2 int,f3 int)
insert into @t
select 'A',7,230
union all select 'A',8,460
union all select 'A',9,580
union all select 'B',7,258
union all select 'B',8,468
union all select 'C',7,563
union all select 'C',9,587

--查询
select * from @t a where f2=(select max(f2) from @t where a.f1=f1)
order by f1


/*--结果:
f1 f2 f3
---- ----------- -----------
A 9 580
B 8 468
C 9 587

(所影响的行数为 3 行)
--*/
zjcxc 元老 2003-11-12
  • 打赏
  • 举报
回复
--为保证顺序,最好加上排序
select * from 表 a where f2=(select max(f2) from 表 where a.f1=f1)
order by f1
zjcxc 元老 2003-11-12
  • 打赏
  • 举报
回复
select * from 表 a where f2=(select max(f2) from 表 where a.f1=f1)

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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