怎么样写这个sql语句?

menglionel 2003-12-24 09:13:12
建立以下的表结构和数据:
create table table1(
name char,
score int)
go
create table table2(
name char,
group char)
go
insert into table1 values('li',70)
go
insert into table1 values('wu',67)
go
insert into table1 values('zhou',80)
go
insert into table1 values('zhang',56)
go
insert into table2 values('li','AAA')
go
insert into table2 values('wu','BBB')
go
insert into table2 values('zhou','AAA')
go
insert into talbe2 values('zhang','BBB')
go
问题是:怎么样查出平均分(score)最高的那个组的组名(group)?
...全文
19 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
menglionel 2003-12-24
  • 打赏
  • 举报
回复
感谢大家的回复,现在看来大家都是用order排序实现的,能用其他方法实现吗?
victorycyz 2003-12-24
  • 打赏
  • 举报
回复
select top 1 b.group
from table1 a join table2 b on a.name=b.name
group by b.group
order by avg(a.score) desc

注意,不要用[name]关联,因为有重名的可能。
zjcxc 元老 2003-12-24
  • 打赏
  • 举报
回复
--下面是测试
declare @table1 table(name char(8),score int)
declare @table2 table(name char(8),[group] char(6))

insert into @table1
select 'li',70
union all select 'wu',67
union all select 'zhou',80
union all select 'zhang',56

insert into @table2
select 'li','AAA'
union all select 'wu','BBB'
union all select 'zhou','AAA'
union all select 'zhang','BBB'

--查询
select top 1 [group],score=avg(score)
from @table1 a join @table2 b on a.name=b.name
group by [group]
order by score desc

/*--结果
group score
------ -----------
AAA 75
--*/
zjcxc 元老 2003-12-24
  • 打赏
  • 举报
回复
select top 1 [group],score=avg(score)
from table1 a join table2 b on a.name=b.name
group by [group]
order by score desc
Rotaxe 2003-12-24
  • 打赏
  • 举报
回复
select top 1 [group] from table2 inner join table1 on table1.name=table2.name group by [group] orderby avg[score] desc

34,590

社区成员

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

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