title: Postgresql : How do I select top n percent(%) entries from each group/category
body: <p>We are new to postgres, we have following query by which we can select top N records from each category.</p>
  
  <pre><code> create table temp (
       gp char,
       val int
   );
  
   insert into temp values ('A',10);
   insert into temp values ('A',8);
   insert into temp values ('A',6);
   insert into temp values ('A',4);
   insert into temp values ('B',3);
   insert into temp values ('B',2);
   insert into temp values ('B',1);
  
   select a.gp,a.val
   from   temp a
   where  a.val in (
                select b.val
                from   temp b
                where  a.gp=b.gp
                order by b.val desc
               limit 2);
  </code></pre>
  
  <p>Output of above query is something like this</p>
  
  <pre><code> gp   val
   ----------
   A    10
   A    8
   B    3
   B    2
  </code></pre>
  
  <p>But our requirement is different, we want to select top n% records from each category where n is not fixed, n is based of some percent of elements in each group.</p>