一個分組取最大值並且排重的SQL

比較典型,記錄在這裏,處理分組獲取最大值後排重的問題。

  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. */ 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章