怎样得到name相同的最大的两个ID?

arclala 2004-09-17 04:53:23
有以下的表,

Name ID
a 1
a 2
b 1
b 2
b 3
c 1
c 2
c 3
c 4
……
怎样得到这样的结果?
Name ID
a 1
a 2
b 2
b 3
c 3
c 4
即得到name相同的最大的两个ID
...全文
118 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
studyzhl 2004-09-17
  • 打赏
  • 举报
回复
select * from 表 a
where id in(
select top 2 * from 表 where name=a.name order by id desc)

当然可以啦!
bernice99 2004-09-17
  • 打赏
  • 举报
回复

select * from 表 a
where id in(
select top 2 * from 表 where name=a.name order by id desc)

可以吗?
outwindows 2004-09-17
  • 打赏
  • 举报
回复
--建表
create table CY_T(Name varchar(10),ID int)
go

insert into CY_T
select 'a', 1
union all select 'a', 2
union all select 'b', 1
union all select 'b', 2
union all select 'b', 3
union all select 'c', 1
union all select 'c', 2
union all select 'c', 3
union all select 'c', 4

--测试
select * from CY_T aa
where ID in (select top 2 ID from CY_T where Name=aa.Name order by ID desc)
order by aa.Name

--结果
/*
----------
Name ID
a 1
a 2
b 2
b 3
c 3
c 4
*/

--删除表
drop table CY_T
木一人 2004-09-17
  • 打赏
  • 举报
回复
----建立测试环境
create table pp (name varchar (5),id int)

insert into pp
select 'a', 1 union
select 'a', 2 union
select 'b', 1 union
select 'b', 2 union
select 'b', 3 union
select 'c', 1 union
select 'c', 2 union
select 'c', 3 union
select 'c', 4


----测试
select * from pp a where a.id in (select top 2 id from pp where name=a.name
order by id desc) order by name
----结果
name id
---- --
a 1
a 2
b 2
b 3
c 3
c 4
zjcxc 元老 2004-09-17
  • 打赏
  • 举报
回复

select * from 表 a
where id in(
select top 2 id from 表 where name=a.name order by id desc)
outwindows 2004-09-17
  • 打赏
  • 举报
回复

select * from 表 aa
where ID in (select top 2 ID from 表 where Name=aa.Name order by ID desc)
order by aa.Name

34,593

社区成员

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

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