日期:2014-05-16  浏览次数:20776 次

关于求第n大值的问题
用test数据库中的test表(表中有两列a b),表如下:
a b
20 1.0
2 24.0
20 40.0
20 3.0
2 37.0
3 13.0
3 30.0
2 14.0
2 22.0
求第3大值。
SET @num1=0;
SET @aa=0;
SELECT a.a,SUM(a.B),MAX(c.b) FROM test a LEFT JOIN
(
SELECT a,b FROM (
SELECT *,@num1:=IF(@aa=a,@num1+1,1) AS pm,@aa:=a AS pm1 FROM test ORDER BY a,b DESC) a WHERE pm=3) c
ON a.a=c.a
GROUP BY a.a;
Query OK, 0 rows affected

Query OK, 0 rows affected

+----+----------+----------+
| a | SUM(a.B) | MAX(c.b) |
+----+----------+----------+
| 2 | 97.0 | 22 |
| 3 | 43.0 | NULL |
| 20 | 44.0 | 1 |
+----+----------+----------+
3 rows in set
看不懂SELECT *,@num1:=IF(@aa=a,@num1+1,1) AS pm,@aa:=a AS pm1 FROM test ORDER BY a,b DESC) a WHERE pm=3,请帮忙解释。谢谢

------解决方案--------------------
引用看不懂SELECT *,@num1:=IF(@aa=a,@num1+1,1) AS pm,@aa:=a AS pm1 FROM test ORDER BY a,b DESC) a WHERE pm=3,请帮忙解释。谢谢