mysql組內排序(分析函式)解決方案
mysql沒有分析函式,要想實現組內排序必須自己實現
sql就不分析了 ,只有幾行,很簡單,基本思想就是自己建立行號。
測試資料:
DROP TABLE test;
CREATE TABLE test( myNAME VARCHAR(10),name1 VARCHAR(10),COUNT1 BIGINT);
DELETE FROM test;
INSERT INTO test VALUES('1','a',2);
INSERT INTO test VALUES('1','b',1);;
INSERT INTO test VALUES('1','c',4);
INSERT INTO test VALUES('1','d',5);
INSERT INTO test VALUES('1','e',7);
INSERT INTO test VALUES('1','f',8);
INSERT INTO test VALUES('2','g',9);
INSERT INTO test VALUES('2','h',0);
INSERT INTO test VALUES('2','i',21);
INSERT INTO test VALUES('2','j',3);
INSERT INTO test VALUES('2','k',4);
INSERT INTO test VALUES('2','1',56);
INSERT INTO test VALUES('3','m',67);
INSERT INTO test VALUES('3','n',89);
INSERT INTO test VALUES('3','o',12);
INSERT INTO test VALUES('3','p',22);
INSERT INTO test VALUES('3','q',23);
INSERT INTO test VALUES('3','r',42);
INSERT INTO test VALUES('3','s',26);
實現sql:
SELECT myNAME, name1, COUNT1
FROM (
SELECT b.myNAME, b.name1, b.count1, IF(@name = b.myNAME, @rank := @rank + 1, @rank := 1) AS rank,@name:=b.myNAME
FROM ( SELECT myNAME, name1, COUNT1 FROM test ORDER BY myNAME ASC, COUNT1 DESC) b,
( SELECT @rownum := 0, @name := NULL, @rank := 0 ) a
) result
WHERE rank<5;
最終輸出: