MYSQL-実現row_number()over(partition by)パケットソート機能



  
  
  
  
  1. MYSQL ORACLE OVER() .  MYSQL , :  
  2.  
  3. 1. :  
  4.  
  5. drop table if exists heyf_t10;  
  6. create table heyf_t10 (empid int ,deptid int ,salary decimal(10,2) );   
  7.  
  8. insert into heyf_t10 values   
  9. (1,10,5500.00),  
  10. (2,10,4500.00),  
  11. (3,20,1900.00),  
  12. (4,20,4800.00),  
  13. (5,40,6500.00),  
  14. (6,40,14500.00),  
  15. (7,40,44500.00),  
  16. (8,50,6500.00),  
  17. (9,50,7500.00);  
  18.  
  19. 2.  :  , .  
  20.  
  21. :  
  22.  
  23. +-------+--------+----------+------+  
  24. | empid | deptid | salary | rank |  
  25. +-------+--------+----------+------+  
  26. | 1 | 10 | 5500.00 | 1 |   
  27. | 2 | 10 | 4500.00 | 2 |   
  28. | 4 | 20 | 4800.00 | 1 |   
  29. | 3 | 20 | 1900.00 | 2 |   
  30. | 7 | 40 | 44500.00 | 1 |   
  31. | 6 | 40 | 14500.00 | 2 |   
  32. | 5 | 40 | 6500.00 | 3 |   
  33. | 9 | 50 | 7500.00 | 1 |   
  34. | 8 | 50 | 6500.00 | 2 |   
  35. +-------+--------+----------+------+  
  36.  
  37.  
  38. 3. SQL   
  39.  
  40. select empid,deptid,salary,rank from (  
  41. select heyf_tmp.empid,heyf_tmp.deptid,heyf_tmp.salary,@rownum:=@rownum+1 ,  
  42. if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank,  
  43. @pdept:=heyf_tmp.deptid  
  44. from (   
  45. select empid,deptid,salary from heyf_t10 order by deptid asc ,salary desc   
  46. ) heyf_tmp ,(select @rownum :=0 , @pdept :null ,@rank:=0) a ) result   
  47. ;  
  48.  
  49. 4.   
  50.  
  51. mysql> select empid,deptid,salary,rank from (  
  52. -> select heyf_tmp.empid,heyf_tmp.deptid,heyf_tmp.salary,@rownum:=@rownum+1 ,  
  53. -> if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank,  
  54. -> @pdept:=heyf_tmp.deptid  
  55. -> from (   
  56. -> select empid,deptid,salary from heyf_t10 order by deptid asc ,salary desc   
  57. -> ) heyf_tmp ,(select @rownum :=0 , @pdept :null ,@rank:=0) a ) result   
  58. -> ;  
  59. +-------+--------+----------+------+  
  60. | empid | deptid | salary | rank |  
  61. +-------+--------+----------+------+  
  62. | 1 | 10 | 5500.00 | 1 |   
  63. | 2 | 10 | 4500.00 | 2 |   
  64. | 4 | 20 | 4800.00 | 1 |   
  65. | 3 | 20 | 1900.00 | 2 |   
  66. | 7 | 40 | 44500.00 | 1 |   
  67. | 6 | 40 | 14500.00 | 2 |   
  68. | 5 | 40 | 6500.00 | 3 |   
  69. | 9 | 50 | 7500.00 | 1 |   
  70. | 8 | 50 | 6500.00 | 2 |   
  71. +-------+--------+----------+------+  
  72. 9 rows in set (0.00 sec)  
  73.  
  74.  
  75.  
  76. MySql N    
  77. select a1.* from article a1   
  78.  
  79. inner join   
  80.  
  81. (select a.type,a.date from article a left join article b   
  82.  
  83. on a.type=b.type and a.date<=b.date    
  84.  
  85. group by a.type,a.date   
  86.  
  87. having count(b.date)<=2  
  88.  
  89. )b1   
  90.  
  91. on a1.type=b1.type and a1.date=b1.date  
  92.  
  93. order by a1.type,a1.date desc