5

I am trying to write a query in Oracle which will return both the pub_id and the maximum total revenue from a titles table which lists pub_id, sales, price. I can get either a listing with pub_id and total revenues for each pub_id with

 SELECT PUB_ID, SUM(SALES*PRICE) as TotalRevenue FROM TITLES GROUP BY PUB_ID;

Or I can get just the MAX(Sales*Price) with

 SELECT MAX(SUM(sales*price)) FROM titles GROUP BY pub_id;

Any ideas how can I get the pub_id out with the maximum of the total revenue?

4 Answers 4

3

You can use the rank function like this

select * from
(
select a.*,rank() over (order by sum_sales desc) r from
(
select pub_id,sum(sales*price) sum_sales from titles group by pub_id
) a
)
where r = 1;    
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Greg. It gives me just what I needed.
1

That's simple with the powerful ORACLE ANALYTICAL FUNCTIONS

Below will give the max revenues for each pub_id.

  select pub_id,REV from 
   (
   select pub_id, (sales*price) as REV,
   max(sales*price) over (partition by pub_id order by 1) as MAX 
   from titles
   )
   where REV=MAX

If you want to determine the pub_id with the maximum revenue:

   select * from
   (
   select pub_id,REV from 
   (
   select pub_id, (sales*price) as REV,
   max(sales*price) over (partition by pub_id order by 1) as MAX 
   from titles
   )
   where REV=MAX order by MAX desc
   )
   where rownum<2

1 Comment

Thanks @bonsvr However keep getting this error "ORA-00923: FROM keyword not found where expected"
1
SELECT PUB_ID, SUM(SALES*PRICE) as TotalRevenue 
FROM TITLES 
GROUP BY PUB_ID
HAVING SUM(SALES*PRICE) = ( SELECT MAX(SUM(SALES*PRICE)) 
                            FROM TITLES 
                            GROUP BY PUB_ID );

Comments

0

There's no really need for analytic functions in this case. The best option would be to group two times one for the sum() and the following time for the max() with the dense_rank option.

select max(pub_id) keep (dense_rank last order by TotalRevenue)
from (
        SELECT PUB_ID, SUM(SALES*PRICE) as TotalRevenue 
        FROM TITLES 
        GROUP BY PUB_ID
    )

1 Comment

Thanks @Alessandro. Not familiar with dense_rank yet but will be soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.