数据分组后的最大指定值记录怎么提取呢?
姓名 数量 类别
孙六 2800 3
李四 2400 1
李五 3600 1
张三 3400 2
王五 2000 1
孙三 2450 2
李九 2455 3
按类别分组后,提取出每个类别,最大的一条记录,不用临时表,循环方式外还有别的吗?
问题点数:20、回复次数:7Top
1 楼dulei115(前途无亮)回复于 2005-11-17 14:25:13 得分 7
按类别分组后,提取出每个类别,数量最大的一条记录
select a.*
from 表 a join (select 类别, max(数量) as 数量
from 表
group by 类别) b on a.类别 = b.类别 and a.数量 = b.数量Top
2 楼rivery(river)回复于 2005-11-17 14:27:43 得分 10
--也可以这样
select *
from 表 a
where not exists(select 1 from 表 where 类别=a.类别 and 数量>a.数量)Top
3 楼coley(唉~眼镜又厚了~)回复于 2005-11-17 14:33:18 得分 0
dulei115() ( ) 信誉:100 我明白
rivery(river) 的看不明白了
Top
4 楼dulei115(前途无亮)回复于 2005-11-17 14:37:04 得分 0
rivery(river)的更高明
not exists(select 1 from 表 where 类别=a.类别 and 数量>a.数量)
同类别中没有比自己的数量(a.数量)更大的Top
5 楼zlp321002(Life Is Good,Let's Shine)回复于 2005-11-17 14:43:00 得分 3
exists 效率高
Top
6 楼coley(唉~眼镜又厚了~)回复于 2005-11-17 14:43:47 得分 0
厉害~给分Top
7 楼wangkenping(找有感觉的妹妹)回复于 2005-11-17 14:57:07 得分 0
declare @t table (n varchar(20),c int,p int)
insert into @t select '孙六',2800,3
union all select '李四',2400,1
union all select '李五',3600,1
union all select '张三',3400,2
union all select '王五',2000,1
union all select '孙三',2450,2
union all select '李九',2455,3
--方法一
select '姓名'=a.n,'数量'=a.c,'类型'=a.p
from @t a where not exists (select * from @t b where a.p=b.p and a.c<b.c)
--方法二
select '姓名'=a.n,'数量'=b.c,'类型'=b.p
from (select p,max(c) c from @t
group by p)b,@t a
where a.p=b.p and a.c=b.c
/*姓名 数量 类型
-------------------- ----------- -----------
孙六 2800 3
李五 3600 1
张三 3400 2 */
方法一你可以这样理解
for p,c in (select * from @t )
if ( not exists ( select * from @t b where a.p=b.p and a.c<b.c ) ) then
OUTPUT
end if;
next
你可以把p,c的数据代到循环中就明白了
第一次循环3,2800 not exists ( select * from @t b where 3=b.p and 2800<b.c )
第二次循环1,2400 not exists ( select * from @t b where 1=b.p and 2400<b.c )
....
第N次循环.....Top




