简体   繁体   中英

How to select top record and count from each group oracle?

How to select the top record and count from each group oracle?

|--------+------------+------------|
| PKid   | name       | occupation |
|--------+------------+------------|
|      1 | John Smith | Accountant |
|      2 | John Smith | Engineer   |
|      3 | Jack Black | Funnyman   |
|      4 | Jack Black | Accountant |
|      5 | John Smith | Manager    |
|--------+------------+------------|

I want to fetch records group by name and order by occupation desc and count. Something like this-

S.no | Name       | Occupation |Count
----------------------------------
1    | John Smith | Accountant | 3
2    | Jack Black | Accountant | 2

I tried something like this but no luck---

select max(PKid) keep(dense_rank first order by occupation) PKid
 , name
 , occupation
from empTbl
group by name;

The way you put it, it is as simple as

SQL> with test (pkid, name, occupation) as
  2    (select 1, 'Smith', 'accountant' from dual union all
  3     select 2, 'Smith', 'engineer'   from dual union all
  4     select 3, 'Black', 'funnyman'   from dual union all
  5     select 4, 'Black', 'accountant' from dual union all
  6     select 5, 'Smith', 'manager'    from dual
  7    )
  8  select name,
  9    min(occupation) occupation,
 10    count(*) cnt
 11  from test
 12  group by name;

NAME  OCCUPATION        CNT
----- ---------- ----------
Black accountant          2
Smith accountant          3

SQL>

if i right understand:

with test (pkid, name, occupation) as
(select 1, 'Smith', 'accountant' from dual union all
select 2, 'Smith', 'engineer'   from dual union all
select 3, 'Black', 'funnyman'   from dual union all
select 4, 'Black', 'accountant' from dual union all
select 5, 'Smith', 'manager'    from dual
)
SELECT name,
    min(occupation)  occupation,
    count(*) cnt
FROM 
(select pkid,
    name,
    first_value(occupation) over (partition by name order by pkid) occupation
from test)
GROUP BY name

Black   funnyman    2
Smith   accountant  3

You can try this query:

SELECT
    ROW_NUMBER() OVER(
        ORDER BY
            COUNT(1) DESC
    ) AS S_NO,
    NAME,
    MIN(OCCUPATION) AS OCCUPATION,
    COUNT(1)
FROM
    EMPTBL
GROUP BY
    NAME;

db<>fiddle demo

cheers!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM