如何在Oracle中编写SQL查询以获取结果:
表“books”有五列:BOOK_ID, 书名, 作者:BOOK_AUTHOR, 价钱, PUBLISH_DATE。 打印过去300天内每位作者最贵的书籍列表?
select book_author,
publish_date
from books
where max(price) and publish_date between (sysdate-300) and sysdate;
答案 0 :(得分:1)
有几种方法可以实现您的目标。这是一个自我排除的联接,应该相当有效。它基本上是说给我一个价格没有更高价格的行;为每个作者。这里有一个经过测试的例子:http://sqlfiddle.com/#!4/86b22/1
select
b.book_author, b.publish_date, b.price
from
books b
left join books b2
on b.book_author = b2.book_author
and b2.price > b.price
and b2.publish_date between (sysdate-300) and sysdate
where
b.publish_date between (sysdate-300) and sysdate
and b2.book_id is null;
如果您有兴趣,可以在我的博客上找到更多此类查询的示例:http://adam-bernier.appspot.com/post/38001/the-self-exclusion-join
答案 1 :(得分:1)
您也可以使用analytics来完成此任务:
select *
from (select book_id,
book_author,
price,
publish_date,
row_number() over (partition by book_author order by price desc) rn
from books
where publish_date >= (sysdate - 300)
)
where rn = 1;