比較典型,記錄在這裏,處理分組獲取最大值後排重的問題。
- /*
- 要求:
- 有一張表,字段和內容如下,
- id category name click download
- ---------------------------------------
- 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 行受影響)
- */