一个分组取最大值并且排重的SQL
比较典型,记录在这里,处理分组获取最大值后排重的问题。[*]/*
[*]要求:
[*]有一张表,字段和内容如下,
[*]id category name clickdownload
[*]---------------------------------------
[*]1 1 A 11 108
[*]2 1 B 12 108
[*]3 2 C 33 34
[*]4 2 D 22 108
[*]5 3 E 21 51
[*]6 3 F 32 68
[*]现在需要按category分组,每个类别只要一个结果,取download最大的那个,并且如果download
[*]最大值有重复的,只取第一个。如上表,我想要取出来的结果是:
[*]id category name click download
[*]--------------------------------------
[*]1 1 A 11 108
[*]4 2 D 22 108
[*]6 3 F 32 68
[*]遇到的问题:现在卡在了如果一个类别的download最大值有重复的情况下,会把最大值重复的行一起取出来。
[*]*/
[*]--测试sql
[*]declare @temp table
[*](
[*] id int,
[*] category int,
[*] name varchar(20),
[*] click int,
[*] download int
[*])
[*]insert into @temp
[*]select 1,1,'A',11,108 union all
[*]select 2,1,'B',12,108 union all
[*]select 3,2,'C',33,34 union all
[*]select 4,2,'D',22,108 union all
[*]select 5,3,'E',21,51 union all
[*]select 6,3,'F',32,68
[*]--主要是2次,一次获取排名,一次排重,排重算法取最大或者最小id都可以
[*]select t.* from @temp t,(
[*]select MAX(t1.id) as id,t1.category from @temp t1,(
[*]select MAX(download) as download,category from @temp
[*]group by category) t2
[*]where t1.category=t2.category and t1.download=t2.download
[*]group by t1.category
[*]) tt
[*]where t.id=tt.id
[*]/*
[*]id category name click download
[*]----------- ----------- -------------------- ----------- -----------
[*]2 1 B 12 108
[*]4 2 D 22 108
[*]6 3 F 32 68
[*]
[*](3 行受影响)
[*]*/
页:
[1]