What was the cost for the most expensive movie(s) in the collection? [duplicate]

旧巷老猫 提交于 2021-02-11 07:04:27

问题


Hey guys I know the code to show the most expensive movie but what's the one that will show the most expensive and ones right below it. I think that's the question. This is the code I got for one movie.

SELECT *
   FROM movie
   WHERE purchase_price = 
    (SELECT MAX(purchase_price) FROM movie);

回答1:


Well since your description is a little ambiguous, to find your prefer solution, you will have to try several of them. For example, you can try by using an ORDER BY Condition. Using this condition, you will retrieve all the movies starting with the most expensive one at the top.

SELECT
    *
FROM
    movie
ORDER BY
    purchase_price DESC;
FETCH FIRST 2 ROWS ONLY

But yet again, there are other solutions you can try as well. You can RANK them by price in a subquery and then fetch all the answers. Another example would be to use between max and min ( or any other value ). You can reach even some more technical and harder to implement solutions.




回答2:


Rank them by price (in a subquery), and fetch the first two. Something like this:

select *
from (select m.*,
             rank() over (order by m.purchase_price desc) rnk
      from movie m
     )
where rnk <= 2

Depending on data you have, you might also consider using ROW_NUMBER or DENSE_RANK analytic functions.




回答3:


If you strictly want the two most expensive movies, you could order the query and use a fetch first clause:

SELECT *
FROM  movie
ORDER BY purchase_price DESC
FETCH FIRST 2 ROWS ONLY

If multiple movies can have the same price, and you want to find all the movies with two most expensive prices, you could use the dense_rank window function:

SELECT *
FROM   (SELECT *, DENSE_RANK() OVER (ORDER BY purchase_price DESC) AS rk
        FROM   movie) m
WHERE  rk <= 2



回答4:


I would rather use the FETCH FIRST 2 ROWS WITH TIES option which will give you the first two most expensive movies and also takes care of multiple movies with the same purchase price

SELECT *
 FROM  movie
ORDER BY purchase_price DESC
FETCH FIRST 2 ROWS ONLY TIES;


来源:https://stackoverflow.com/questions/65087237/what-was-the-cost-for-the-most-expensive-movies-in-the-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!