SQL分组[重金悬赏]

txws1119 2009-04-03 02:45:09
编号 类别 名称 分数
1 语文 A 90
2 语文 B 80
3 数学 C 70

输出结果:

1 语文 A 90
3 数学 C 70

请问各位大大,这个SQL应该如何写的
...全文
62 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
claro 2009-04-03
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 txws1119 的回复:]
好象不能用啊,1代表什么?不好意思,我比较菜还望多多指点
[/Quote]

/*exists 和select 1的用法解释:
exist 即存在。
select 1 from table

select * from table 作用上来说是没有差别的,都是查看是否有记录,一般是作条件用的。
select 1 from 中的1是一常量,查到的所有行的值都是它,但从效率上来说,1>*,因为不用查字典表。
*/
txws1119 2009-04-03
  • 打赏
  • 举报
回复
感谢大家~~感谢CSDN
Zoezs 2009-04-03
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 txws1119 的回复:]
好象不能用啊,1代表什么?不好意思,我比较菜还望多多指点[/Quote]
1 就代表1 意思是,(select 1 from tb where 编号=t.编号 and 分数>t.分数)只要有就会有1
没有就是null。
claro 2009-04-03
  • 打赏
  • 举报
回复
/*
编号 类别 名称 分数
1 语文 A 90
2 语文 B 80
3 数学 C 70

输出结果:

1 语文 A 90
3 数学 C 70

请问各位大大,这个SQL应该如何写的
*/
create table #t (编号 int, 类别 varchar(20), 名称 varchar(20), 分数 int)
insert into #t
select 1,'语文','A',90 union
select 2,'语文','B',80 union
select 3,'数学','C',70

select a.*
from #t a
join (select 类别,max(分数) 分数 from #t b group by 类别) b on a.类别=b.类别 and a.分数=b.分数

编号 类别 名称 分数
1 语文 A 90
3 数学 C 70

drop table #t
txws1119 2009-04-03
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 HEROWANG 的回复:]
引用楼主 txws1119 的帖子:
编号 类别 名称 分数
1 语文 A 90
2 语文 B 80
3 数学 C 70

输出结果:

1 语文 A 90
3 数学 C 70

请问各位大大,这个SQL应该如何写的


select * from tb t where not exists(select 1 from tb where 编号=t.编号 and 分数>t.分数)

编号 类别 名称 分数
1 语文 A 90
3 数学 C 70
[/Quote]

好象不能用啊,1代表什么?不好意思,我比较菜还望多多指点
fcuandy 2009-04-03
  • 打赏
  • 举报
回复
看不懂是按分数,还是按名称,或者各自MAX聚合。
等不到来世 2009-04-03
  • 打赏
  • 举报
回复
select * from tb where 编号 in (select min(编号) from tb group by 类别)
---or:
select * from tb t where not exists(select 1 from tb where 类别=t.类别 and 编号<t.编号)
  • 打赏
  • 举报
回复
[Quote=引用楼主 txws1119 的帖子:]
编号 类别 名称 分数
1 语文 A 90
2 语文 B 80
3 数学 C 70

输出结果:

1 语文 A 90
3 数学 C 70

请问各位大大,这个SQL应该如何写的
[/Quote]

select * from tb t where not exists(select 1 from tb where 编号=t.编号 and 分数>t.分数)

编号 类别 名称 分数
1 语文 A 90
3 数学 C 70
ks_reny 2009-04-03
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 txws1119 的回复:]
引用 2 楼 Zoezs 的回复:
SQL code
select * from (select id,max(分数) from Tab group by id) b


B是什么?
[/Quote]
B是別名.
jia_guijun 2009-04-03
  • 打赏
  • 举报
回复
select * from tb a join (select 类别,max(分类) as 分数 from tb group by 类别) b on a.类别=b.类别 and a.分数=b.分数
txws1119 2009-04-03
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 Zoezs 的回复:]
SQL code
select * from (select id,max(分数) from Tab group by id) b
[/Quote]

B是什么?
rucypli 2009-04-03
  • 打赏
  • 举报
回复
select *
from tb
where id in
(
select 类别,min(编号)
from tb
group by 类别
)
Zoezs 2009-04-03
  • 打赏
  • 举报
回复

select * from TAB a,(select id,max(分数) from Tab group by id) b where a.id=b.id

jia_guijun 2009-04-03
  • 打赏
  • 举报
回复
select 编号,类别,名称,max(分类) as 分类 from tb group by 类别
Zoezs 2009-04-03
  • 打赏
  • 举报
回复

select * from (select id,max(分数) from Tab group by id) b
claro 2009-04-03
  • 打赏
  • 举报
回复
结果显示分组的最大分数?

22,210

社区成员

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

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