求一个SQL语句,比较麻烦

pam 2007-10-22 12:09:23
有这样的一个表格

单位 金额 分类
a 10 1
a 8 2
b 1 1
c 1 2

我要得到每个单位分类值最大的记录,结果如下所示

单位 金额 分类
a 8 2
b 1 1
c 1 2

请问这个sql该怎么写
...全文
69 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2007-10-22
  • 打赏
  • 举报
回复
create table tb(单位 varchar(10),金额 int,分类 int)
insert into tb values('a', 10, 1 )
insert into tb values('a', 8 , 2 )
insert into tb values('b', 1 , 1 )
insert into tb values('c', 1 , 2 )
go

--按记录顺序取第一条
select a.* from tb a where 分类 = (select top 1 分类 from tb where 单位=a.单位)
/*
单位 金额 分类
---------- ----------- -----------
a 10 1
b 1 1
c 1 2
*/

--取最小
select a.* from tb a where 分类=(select min(分类) from tb where 单位=a.单位)
/*
单位 金额 分类
---------- ----------- -----------
a 10 1
b 1 1
c 1 2
*/

--取最大
select a.* from tb a where 分类=(select max(分类) from tb where 单位=a.单位)
/*
单位 金额 分类
---------- ----------- -----------
c 1 2
b 1 1
a 8 2
*/

--随机取
select a.* from tb a where 分类=(select top 1 分类 from tb where 单位=a.单位 order by newid())
/*
单位 金额 分类
---------- ----------- -----------
a 8 2
b 1 1
c 1 2

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

drop table tb

yxh198358 2007-10-22
  • 打赏
  • 举报
回复
select * from tablename where 分类 = (select max(分类) from tablename )
guoli0813 2007-10-22
  • 打赏
  • 举报
回复

,我得错了,没有看清题意!
guoli0813 2007-10-22
  • 打赏
  • 举报
回复
select*
from table1
from table1,(select 分类,金额 from table1 group by 分类,金额) aa
where aa.分类=table1.分类


测试一下,我没有测试
dawugui 2007-10-22
  • 打赏
  • 举报
回复
--按记录顺序取第一条
select a.* from tb a where 分类=(select top 1 分类 from tb where where 单位=a.单位)

--取最小
select * from @test a where 分类=(select min(分类) from tb where where 单位=a.单位)

--取最大
select * from @test a where 分类=(select max(分类) from tb where where 单位=a.单位)

--随机取
select * from @test a where 分类=(select top 1 分类 fromtb where where 单位=a.单位 order by newid())

dawugui 2007-10-22
  • 打赏
  • 举报
回复
select a.* from tb where 分类 = (select max(分类) from tb where 单位=a.单位)
pt1314917 2007-10-22
  • 打赏
  • 举报
回复
select a.* from tb where 分类 = (select max(分类) from tb where 单位=a.单位)

22,209

社区成员

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

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