Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL - Group by with ROWNUM in Having clause?

Tags:

sql

oracle

plsql

I'm trying to get the user in the database who has the ownership over the biggest segment in the database. For this I'm trying:

SELECT owner, MAX(bytes) 
FROM SYS.DBA_SEGMENTS
GROUP BY owner
HAVING ROWNUM <= 1;

This, however, returns "not a GROUP BY expression". Why can't I select the first row only? How can I write this query? Thank you!

like image 761
lte__ Avatar asked Nov 05 '16 22:11

lte__


2 Answers

You can. In Oracle 12c+, you can do:

SELECT owner, MAX(bytes) 
FROM SYS.DBA_SEGMENTS
GROUP BY owner
ORDER BY MAX(bytes) DESC
FETCH FIRST ROW ONLY;

Note the ORDER BY.

In earlier versions you need a subquery:

SELECT o.*
FROM (SELECT owner, MAX(bytes) 
      FROM SYS.DBA_SEGMENTS
      GROUP BY owner
      ORDER BY MAX(bytes) DESC
     ) o
WHERE rownum = 1;
like image 154
Gordon Linoff Avatar answered Oct 24 '22 23:10

Gordon Linoff


In earlier versions, you can also use (just one pass over the data):

select max(owner) keep (dense_rank last order by bytes nulls first) as owner,
       max(bytes) as bytes
from   sys.dba_segments;
like image 43
mathguy Avatar answered Oct 24 '22 21:10

mathguy