2

Guys I have the following query:

select count(*) AS num_items
       from desc_look
       group by dept

This query returns the number of items in each department. However I can't get ONLY the department with the higher number of items.

I've been trying to use this to retrieve the name and id of the department with most items

select dept, desc_up
from desc_look
where (select count(*) AS num_items
       from desc_look
       group by dept)

However I keep getting an error ORA-00936 and I don't know why. I know I can't user MAX(COUNT(*)) but is there a way to workaround this?

SaintLike
  • 7,491
  • 8
  • 36
  • 62
  • Does the `desc_up` column always contain the department name that matches `dept_id` of the same row, i.e. both the department name and id are store in the `desc_look` table? – Mick Mnemonic Mar 30 '15 at 18:52

4 Answers4

4
select * from
(
    select count(*) AS num_items
    from desc_look
    group by dept
    order by count(*) desc
) tmp
WHERE ROWNUM = 1;

Also have a look on howto limit the records in Oracle.

Community
  • 1
  • 1
juergen d
  • 186,950
  • 30
  • 261
  • 325
2

This version is basically the same as juergen's, but using an analytic function instead of an aggregate (GROUP BY) for counting:

SELECT t.dept, t.desc_up FROM
  (SELECT dept, desc_up,
   COUNT(*) over (partition BY dept) dept_count
   FROM desc_look
   ORDER BY dept_count DESC
  ) t
WHERE rownum = 1

If you're on Oracle 12, the inline view is not needed because you can use the row-limiting clause (FETCH FIRST ...):

SELECT dept, desc_up,
  COUNT(*) over (partition BY dept) dept_count
FROM desc_look
ORDER BY dept_count DESC
FETCH FIRST 1 ROW ONLY
Mick Mnemonic
  • 7,403
  • 2
  • 23
  • 27
0

i think this may help you

select count(*) AS num_items
       from desc_look
       group by dept
       order by count(*) desc
       limit 1
Allan
  • 16,316
  • 4
  • 49
  • 63
0

You might try something like this:

SELECT dept, num_items FROM (
    SELECT dept, COUNT(*) AS num_items
         , ROW_NUMBER() OVER ( ORDER BY COUNT(*) DESC ) AS rn
      FROM desc_look
     GROUP BY dept
) WHERE rn = 1;
David Faber
  • 11,549
  • 2
  • 25
  • 40