Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

To take top 20 percentage of records

user13527496Nov 17 2017 — edited Nov 24 2017

Hi Guys,

I am having below table

 

 

IDAm_1Am_2Am_3
120 20
2 3031
3151515
41010

I need to take the top 20 percentage of values based on each Am_1,am_2,am_3 columns. For eg sort am_1 in desc and get top 2 id's

Output required

 

IDAm_1Am_2Am_3
120 20
2 3031
31515
4

Table Queries

create table source_table(id number,am_1 number,am_2 number,am_3 number);

insert into table source_table values (1,20,'',20);

insert into table source_table values (2,'',30,31);

insert into table source_table values (3,15,15,15);

insert into table source_table values (4,10,10,'');

> select * from source_table;

1       20      NULL    20

2       NULL    30      31

3       15      15      15

4       10      10      NULL

Query i have used:

SELECT   t.n_cust,

         t.am_1

FROM     (

SELECT   a.id,

                           a.am_1,

                           row_number() over (ORDER BY cast(a.am_1 AS DECIMAL(8,7)) DESC) AS rank

                  FROM     (

                                    SELECT   id,

                                             am_1

                                    FROM     source_table

                                    ORDER BY am_1 DESC ) a) t

join

         (

                SELECT count(1) AS count

                FROM   source_table

                AND    am_1 is not null )f

WHERE    t.rank < 0.2*f.count

ORDER BY am_1 DESC;

Assuming that there are more than 10 records so that top 20 percentage would be 2 values. 

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 22 2017
Added on Nov 17 2017
15 comments
2,507 views