一个关于分组的问题,求助

kk19840210 2007-01-30 04:17:54
create table #tab (A varchar(1),B int)

insert into #tab values ('a',1)

insert into #tab values ('a',2)

insert into #tab values ('a',3)

insert into #tab values ('b',1)

insert into #tab values ('b',2)

insert into #tab values ('b',3)
求出 'a' 和'b' 中最大的两个值
需求结果
A B

a 3
a 2
b 3
b 2
...全文
204 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
prcgolf 2008-04-29
  • 打赏
  • 举报
回复
select a,b from (select *,row_number()over(partition by a order by b desc) as x from #tab) y
where x<=2 order by a,x
kk19840210 2008-01-14
  • 打赏
  • 举报
回复
2

select * from #tmp a where (select count(1) from #tmp where type=a.type and grade>a.grade)<2 order by [type]

name type grade
---------- ---------- ----------
A com 98
B com 82
C eng 82
A eng 92
A math 85

(5 行受影响)

hrb2008 2007-01-30
  • 打赏
  • 举报
回复
select * from #tab tmp
where (select count(1) from #tab where A=tmp.A and B>tmp.B)<2
leo_lesley 2007-01-30
  • 打赏
  • 举报
回复
select a,b
from #tab a
where 2>(select count(1) from #tab where a = a.a and b>a.b)
rookie_one 2007-01-30
  • 打赏
  • 举报
回复
select * from #tab t1
where B in(select top 2 B from #tab where A=t1.A order by B desc)
marco08 2007-01-30
  • 打赏
  • 举报
回复
create table #tab (A varchar(1),B int)

insert into #tab values ('a',1)

insert into #tab values ('a',2)

insert into #tab values ('a',3)

insert into #tab values ('b',1)

insert into #tab values ('b',2)

insert into #tab values ('b',3)

select * from #tab tmp
where (select count(*) from #tab where A=tmp.A and B>tmp.B)<2
order by A, B desc

--result
A B
---- -----------
a 3
a 2
b 3
b 2
marco08 2007-01-30
  • 打赏
  • 举报
回复
select * from #tab tmp
where (select count(*) from #tab where A=tmp.A and B>tmp.B)<2
chuifengde 2007-01-30
  • 打赏
  • 举报
回复
select * from #tab a where b in(select top 2 b from #tab where a=a.a order by b desc)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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