为每件艺术品选择最高价格

时间:2021-03-25 12:18:30

标签: sql select

我必须为每篇文章选择最高价格

我有那个桌子:

create table shop (
article int(4) unsigned zerofill default '0000' not null,
dealer char(20) default '' not null,
price double(16,2) default '0.00' not null,
primary key (article, dealer));

insert into shop values(1, 'A', 3.45), (1,'B', 3.99),
(2, 'A', 10.99), (3, 'B', 1.45), (3, 'C', 1.69), 
(3, 'D', 1.25), (4, 'D', 19.95); 

并尝试执行此代码:

select article, dealer, max(price) from shop group by article;

但它显示错误的经销商

enter image description here

价格 3.99 在经销商 B 处,但显示为 A

2 个答案:

答案 0 :(得分:0)

您可以使用相关子查询:

select s.*
from shop s
where s.price = (select max(s2.price) from shop s2 where s2.article = s.article);

答案 1 :(得分:0)

架构和输入语句:

 create table shop ( article int(4) unsigned zerofill default '0000' not null, dealer char(20) default '' not null, price double(16,2) default '0.00' not null, primary key (article, dealer));
 
 insert into shop values(1, 'A', 3.45), (1,'B', 3.99), (2, 'A', 10.99), (3, 'B', 1.45), (3, 'C', 1.69), (3, 'D', 1.25), (4, 'D', 19.95);

查询:

with cte as 
         (
             select article, dealer, price, max(price)over(partition by article)maxprice from shop
         )
         Select article,dealer,price from cte where price=maxprice;

输出:

 |article | dealer | price|
 |------: | :----- | ----:|
 |   0001 | B      |  3.99|
 |   0002 | A      | 10.99|
 |   0003 | C      |  1.69|
 |   0004 | D      | 19.95|

db<>fiddle here

相关问题