简体   繁体   English

Select 最高值链接到标题 - sql

[英]Select highest value linked to title - sql

I am trying to select the highest pair from a table that has been created by joining (combining) two tables.我正在尝试 select 通过连接(组合)两个表创建的表中的最高对。 I guess I should use a nested query but I'm not sure how.我想我应该使用嵌套查询,但我不确定如何。 I also came around a similar question that seems a bit less complex, but I am struggling to implement it into my problem.我也遇到了一个类似的问题,似乎不太复杂,但我正在努力将它实施到我的问题中。

Similar question: How to select max timestamp from each currency pair SQL?类似的问题: 如何从每个货币对 SQL 中获取 select 的最大时间戳?

My tables:我的桌子:

Book:书:

title标题 publisher出版商 price价格 sold
book1书1 A一个 5 5 300 300
book2书2 B 15 15 150 150
book3书3 A一个 8 8 350 350

Publisher:出版商:

code代码 name姓名
A一个 ABook一本书
B BBook
C C CBook图书

My query:我的查询:

SELECT b.titel, p.name, max(b.price*b.sold) as 'Revenue"
FROM publisher p, book b
WHERE p.code = b.publisher

Gives:给出:

title标题 publisher出版商 Revenue收入
book1书1 ABook一本书 1500 1500
book2书2 BBook 2250 2250
book3书3 ABook一本书 2800 2800

Desired output:所需的 output:

title标题 publisher出版商
book2书2 BBook
book3书3 ABook一本书

How to alter my query to get the highest revenue per book title and the corresponding publisher?如何更改我的查询以获得每本书标题和相应出版商的最高收入?

You can use this query:您可以使用此查询:

SELECT b.titel, p.name FROM publisher p, book b WHERE p.code = b.publisher order by b.price*b.sold desc SELECT b.title, p.name FROM publisher p, book b WHERE p.code = b.publisher order by b.price*b.sold desc

You can use row_number window function to select the appropriate row for each group.您可以使用row_number window function 到 select 每个组的适当行。

Your desired results don't align with your description (do you want a revenue column or not?), however this produces your desired output.您想要的结果与您的描述不一致(您是否想要收入列?),但是这会产生您想要的 output。 Note the use of modern (for 30 years) ansi join syntax:注意使用现代(30 年)ansi join 语法:

with sold as (
    select *, Row_Number() over(partition by publisher order by (price * sold) desc) rn
    from book b join publisher p on p.code=b.publisher
)
select title, name Publusher
from sold
where rn=1

I solved it by using a nested query (I guess?)我通过使用嵌套查询解决了它(我猜?)

select b.title, p.name
from boek b join publisher p on p.code = b.publisher
where b.sold*b.price = (select max(sold*price)
                     from book t2
                     where t2.publisher = b.publisher
                    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM