SQL(不限哪种sql, 下面例子中本人用的是MySQL)中怎么样查询每个分组的前n名?
有表如下,想找出最便宜的前n种水果
type variety price
apple gala 2.79
apple fuji 0.24
apple limbertwig 2.87
orange valencia 3.59
orange navel 9.36
pear bradford 6.05
pear bartlett 2.14
cherry bing 2.55
cherry chelan 6.33
n为2时,SQL很好写,结果集如下
apple fuji 0.24
apple gala 2.79
cherry bing 2.55
cherry chelan 6.33
orange valencia 3.59
orange navel 9.36
pear bartlett 2.14
pear bradford 6.05
n为3时,结果集如下
apple fuji 0.24
apple gala 2.79
apple limbertwig 2.87
cherry bing 2.55
cherry chelan 6.33
cherry null 0
orange valencia 3.59
orange navel 9.36
orange null 0
pear bartlett 2.14
pear bradford 6.05
pear null 0
求帮助csdn高手,这种情况呢? n变化的时候,有没有通用的办法?
(csdn好怪异,好不容易把tab一个个换成了空格了,结果这里的空格与字符不等宽…)
表的创建sql:
create table fruit(
id int auto_increment primary key,
type varchar(10),
variety varchar(10),
price double(10,2)
);
insert into fruit(type, variety, price)
values(“apple” , “gala” , 2.79),
(“apple” , “fuji” , 0.24),
(“apple” , “limbertwig” , 2.87),
(“orange” , “valencia” , 3.59),
(“orange” , “navel” , 9.36),
(“pear” , “bradford” , 6.05),
(“pear” , “bartlett” , 2.14),
(“cherry” , “bing” , 2.55),
(“cherry” , “chelan” , 6.33);
n为2时的sql:
set @cnt :=0, @num := 0, @type := “”;
select t.type, t.variety, t.price,
@num := if(@type = type, @num + 1, 1) as row_number
,@type := type
from
(select type, variety, price
from fruit
order by type asc, price asc
) as t
group by t.type, t.price, t.variety
having row_number <= 2;
有表如下,想找出最便宜的前n种水果
type variety price
apple gala 2.79
apple fuji 0.24
apple limbertwig 2.87
orange valencia 3.59
orange navel 9.36
pear bradford 6.05
pear bartlett 2.14
cherry bing 2.55
cherry chelan 6.33
n为2时,SQL很好写,结果集如下
apple fuji 0.24
apple gala 2.79
cherry bing 2.55
cherry chelan 6.33
orange valencia 3.59
orange navel 9.36
pear bartlett 2.14
pear bradford 6.05
n为3时,结果集如下
apple fuji 0.24
apple gala 2.79
apple limbertwig 2.87
cherry bing 2.55
cherry chelan 6.33
cherry null 0
orange valencia 3.59
orange navel 9.36
orange null 0
pear bartlett 2.14
pear bradford 6.05
pear null 0
求帮助csdn高手,这种情况呢? n变化的时候,有没有通用的办法?
(csdn好怪异,好不容易把tab一个个换成了空格了,结果这里的空格与字符不等宽…)
表的创建sql:
create table fruit(
id int auto_increment primary key,
type varchar(10),
variety varchar(10),
price double(10,2)
);
insert into fruit(type, variety, price)
values(“apple” , “gala” , 2.79),
(“apple” , “fuji” , 0.24),
(“apple” , “limbertwig” , 2.87),
(“orange” , “valencia” , 3.59),
(“orange” , “navel” , 9.36),
(“pear” , “bradford” , 6.05),
(“pear” , “bartlett” , 2.14),
(“cherry” , “bing” , 2.55),
(“cherry” , “chelan” , 6.33);
n为2时的sql:
set @cnt :=0, @num := 0, @type := “”;
select t.type, t.variety, t.price,
@num := if(@type = type, @num + 1, 1) as row_number
,@type := type
from
(select type, variety, price
from fruit
order by type asc, price asc
) as t
group by t.type, t.price, t.variety
having row_number <= 2;
解决方案
40