比较典型,记录在这里,处理分组获取最大值后排重的问题。

 
  
  1. /*  
  2. 要求:
  3. 有一张表,字段和内容如下,  
  4. id category name click  download  
  5. ---------------------------------------  
  6. 1     1            A      11     108  
  7. 2     1            B      12     108  
  8. 3     2            C      33     34  
  9. 4     2            D      22     108  
  10. 5     3            E      21     51  
  11. 6     3            F      32     68  
  12. 现在需要按category分组,每个类别只要一个结果,取download最大的那个,并且如果download  
  13. 最大值有重复的,只取第一个。如上表,我想要取出来的结果是:  
  14. id category name click download  
  15. --------------------------------------  
  16. 1      1           A     11       108  
  17. 4      2           D     22       108  
  18. 6      3           F     32       68  
  19. 遇到的问题:现在卡在了如果一个类别的download最大值有重复的情况下,会把最大值重复的行一起取出来。  
  20. */  
  21. --测试sql
  22. declare @temp table   
  23. (  
  24.     id int,  
  25.     category int,  
  26.     name varchar(20),  
  27.     click int,  
  28.     download int 
  29. )  
  30. insert into @temp 
  31. select 1,1,'A',11,108 union all 
  32. select 2,1,'B',12,108 union all 
  33. select 3,2,'C',33,34 union all 
  34. select 4,2,'D',22,108 union all 
  35. select 5,3,'E',21,51 union all 
  36. select 6,3,'F',32,68   
  37. --主要是2次,一次获取排名,一次排重,排重算法取最大或者最小id都可以 
  38. select t.* from @temp t,(  
  39. select MAX(t1.id) as id,t1.category from @temp t1,(  
  40. select MAX(download) as download,category from @temp   
  41. group by category) t2  
  42. where t1.category=t2.category and t1.download=t2.download  
  43. group by t1.category  
  44. ) tt  
  45. where t.id=tt.id  
  46. /*  
  47. id          category    name                 click       download  
  48. ----------- ----------- -------------------- ----------- -----------  
  49. 2           1           B                    12          108  
  50. 4           2           D                    22          108  
  51. 6           3           F                    32          68  
  52.  
  53. (3 行受影响)  
  54. */