如何抽取某字段值最大的记录

clkun 2009-07-02 11:32:00
表a(id是自动编号)
id name shu
1 a 1
2 a 2
3 a 3
4 b 1
5 b 2
6 c 1
7 d 1

要求就是name值相同的取出 shu 的值最大的一条记录,上面过滤一下结果如果下:

id name shu
3 a 3
5 b 2
6 c 1
7 d 1

先谢了。
...全文
47 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
hecker728 2009-07-02
  • 打赏
  • 举报
回复

declare @t table(id int,name varchar(5),shu int)
insert @t
select 1,'a',1 union all
select 2,'a',2 union all
select 3,'a',3 union all
select 4,'b',1 union all
select 5,'b',2 union all
select 6,'c',1 union all
select 7,'d',1

select a.id,a.name,b.shu from @t a right join
(select name,max(shu) as shu from @t group by name) b on
a.name=b.name where a.shu=b.shu order by id asc

/*-------------------------
id name shu
3 a 3
5 b 2
6 c 1
7 d 1
---------------------------*/
dawugui 2009-07-02
  • 打赏
  • 举报
回复
select m.* from tb m where not exists(select 1 from tb n where name = m.name and shu > m.shu)

select m.* from tb m where shu = (select max(shu) from tb n where name = m.name)
jiangshun 2009-07-02
  • 打赏
  • 举报
回复


if object_id('[表a]') is not null drop table [表a]
create table [表a]([id] int,[name] varchar(1),[shu] int)
insert [表a]
select 1,'a',1 union all
select 2,'a',2 union all
select 3,'a',3 union all
select 4,'b',1 union all
select 5,'b',2 union all
select 6,'c',1 union all
select 7,'d',1

select * from [表a] t where not exists(select 1 from [表a] where t.[name]=[name] and t.id<id)


/*
id name shu
----------- ---- -----------
3 a 3
5 b 2
6 c 1
7 d 1

(所影响的行数为 4 行)
*/

drop table [表a]
izbox 2009-07-02
  • 打赏
  • 举报
回复

Select * from #a a where not exists (select 1 from #a b where b.name=a.name and b.depID>a.depID)
feixianxxx 2009-07-02
  • 打赏
  • 举报
回复
select name,max(shu) from a
group by name
--or
Select * from tb a where not exists (select 1 from a where name=a.name and a.shu>shu
--or
select * from tb a aa where shu =(select max(shu) from a where aa.name=name )
ks_reny 2009-07-02
  • 打赏
  • 举报
回复

Select * from tb a where not exists (select 1 from name=a.name and a.shu>shu)
izbox 2009-07-02
  • 打赏
  • 举报
回复

select name,max(shu) from a
group by name
edithbianyuhua 2009-07-02
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 flairsky 的回复:]
select name,max(shu) from a
group by name

[/Quote]

测试过没有问题

flairsky 2009-07-02
  • 打赏
  • 举报
回复
select name,max(shu) from a
group by name
drysea 2009-07-02
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ks_reny 的回复:]
SQL codeSelect*from tb awherenotexists (select1from name=a.nameand a.shu>shu)
[/Quote]

up
SQL77 2009-07-02
  • 打赏
  • 举报
回复
SELECT * FROM TB T WHERE NOT EXISTS(SELECT 1 FROM TB WHERE ID<>T.ID AND NAME=T.NAME AND T.SHU<SHU)

34,576

社区成员

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

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