求思路 分组求最大值

carl900 2012-05-17 04:14:51
数据:
a,1
a,2
a,3
b,2
b,1


想求出 a.3,b,2的数据
...全文
122 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
SQL_2008 2012-05-17
  • 打赏
  • 举报
回复

create table #tb(col1 varchar(5),col2 int)
insert into #tb values('a',1),('a',2),('a',3),('b',2),('b',1);

select col1,col2 from
(select*,row_number()over(partition by col1 order by col2 desc)rin from #tb)fin
where fin.rin=1
drop table #tb
/*
(5 row(s) affected)

col1 col2
----- -----------
a 3
b 2

(2 row(s) affected)
*/
迪迦凹凸曼 2012-05-17
  • 打赏
  • 举报
回复

或者
select d.* from test a
cross apply
(
select top (1) col1,col2 from test b where b.col1=a.col1 order by col1,col2 desc
) d
group by d.col1,d.col2
  • 打赏
  • 举报
回复

或者
select * from test a
where a.col2=(select max(col2) from test b where a.col1=b.col2)
  • 打赏
  • 举报
回复

select * from test t
where not exists(select 1 from test m where t.col1=m.col1 and t.col2<m.col2)
天-笑 2012-05-17
  • 打赏
  • 举报
回复
row_number() 函数可以解决

22,209

社区成员

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

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