Вопрос

I'm not sure how to get the max of the sum. I thought i could just display it in descending order and then use "rownum=1" but that didnt work. Any suggestions? Here's my code.

select ca_make,  sum(ma_cost)
from cab join maintain on ca_cabnum = ma_cabnum 
Where rownum =1
group by ca_make
order by sum(ma_cost) desc
Это было полезно?

Решение

ROWNUM() is applied before the ORDER BY. You need to use a sub-query:

select * from (
    select ca_make,  sum(ma_cost)
    from cab join maintain on ca_cabnum = ma_cabnum 
    group by ca_make
    order by sum(ma_cost) desc
    )
where rownum = 1

There are several different ways of implementing [top-n] queries in Oracle. Find out more by searching SO for [oracle] [top-n].

Другие советы

First of all, you probably want to use LEFT JOIN. By using JOIN, you're excluding all cabs that have had no maintenance at all. (obviously, this won't matter for finding the highest cost, but it will make a difference when looking for the lowest cost; and it would seriously skew any stats you tried to compile from this query).

Now, to answer your question... try this:

select * from
  (select ca_make,  sum(ma_cost)
  from cab 
    left join maintain on ca_cabnum = ma_cabnum 
  group by ca_make
  order by sum(ma_cost) desc)
where rownum = 1

here is a good explanation of ROWNUM. Your case is addressed specifically, a little less than half-way down the page (but the whole page is probably worth a read, if you're going to use the feature).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top