一个有难度的SQL语句!

表如下
code class price
1 a 1
2 a 1.1
3 b 2
4 a 0.9
5 c 2.2
6 a 2
7 b 3
8 b 1.6
9 c 2
10 c 1
11 b 1.3
现在要按CLASS分别取处PRICE前2名的记录,如下
code class price
6 a 2
2 a 1.1
7 b 3
3 b 2
5 c 2.2
9 c 2
---------------------------------------------------------------

select * from tab a where (select count(*) from tab b where b.class = a.class and b.price > a.price) < 2
order by class,price desc

(已通过测试,但不支持某种类型价格有并列第二的情况,思路就是这样,怎么解决并列的问题自己想想吧,这几天头痛,不想了)

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus