如何使用2个表格获得类别中最昂贵的项目?

时间:2017-09-26 08:37:40

标签: sql postgresql

我试图仅显示具有最昂贵物品的类别。

我尝试过,通过查询,我得到了所有类别和每个类别中最贵的项目的价格,但我不知道如何做到只获得最贵的一个类别。

select categories.category ,max(purchase_price) as dyrast_bok
from categories
inner join books on categories.category_id = books.category_id
group by categories.category;

表格:

CATEGORIES ( category_id (PK), category )

BOOKS ( book_id (PK), title, publisher_id (FK), published_year,
 purchase_price, category_id (FK),purchase_date, pages,
 book_type_id (FK) )

4 个答案:

答案 0 :(得分:1)

select categories.category ,purchase_price as dyrast_bok
from categories
inner join books on categories.category_id = books.category_id
where purchase_price in (select max(purchase_price) from books)

答案 1 :(得分:0)

您可以尝试按max(purchase_price) desc订购,然后选择第一个:

select *
from (your query with order by max(purchase_price) desc)
limit 1

答案 2 :(得分:0)

您只需要使用别名,这样您就可以在GROUP BY部分重复使用它们,并使用top 1max(b.purchase_price)订购时获得最高结果。

这是你的查询:

select top 1 c.category , max(b.purchase_price) as dyrast_bok
from categories c
inner join books b on categories.category_id = books.category_id
order by dyrast_bok 
group by c.category;

答案 3 :(得分:0)

简单方法:拥有一个返回max purchase_price的子查询。

select c.category, b.purchase_price as dyrast_bok
from categories c
inner join books b on c.category_id = b.category_id
where b.purchase_price = (select max(purchase_price) from books)

如果出现平局,将返回两本书!

替代解决方案:

select c.category, b.purchase_price as dyrast_bok
from categories c
inner join books b on c.category_id = b.category_id
order by b.purchase_price desc
fetch first 1 row

不包含关系,只返回一行。 (AFAIK Postgresql不支持FETCH FIRST WITH TIES。)