mysql实现over()开窗函数功能

Mysql实现开窗函数功能:

参考:http://stackoverflow.com/questions/3333665/rank-function-in-mysql

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
---------------------------------------------
--不是做分区,只做排名---
SELECT    first_name,
          age,
          gender,
          @curRank := @curRank + 1 AS rank
FROM      person p, (SELECT @curRank := 0) r
ORDER BY  age;


--分区排名--
SELECT    a.first_name,
      a.age,
      a.gender,
        count(b.age)+1 as rank
FROM  person a 
left join person b 
on a.age>b.age and a.gender=b.gender 
group by  a.first_name,
      a.age,
      a.gender


 
  
 
  
 
  
 
  
 
  
 
 

你可能感兴趣的:(mysql)