Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

PostgreSQL- Select first row in each GROUP BY group

$
0
0
I want to select the first row of each group grouped by the PostgreSQL keyword GROUP BY. Suppose I am working on purchase reporting and I want to select the customer who has a max value of the price.

I have the following table

CREATETABLEorders
(
          idserialnotnull,
          nametext,
          itemQtyinteger,
          pricedecimal
);

--Insert some records
insertintoorders(name,itemqty,price)
  values('Ashish',2,200);
insertintoorders(name,itemqty,price)
  values('Naina',8,300); 
insertintoorders(name,itemqty,price)
  values('Mamta',10,2000);
insertintoorders(name,itemqty,price)
  values('Ashish',4,500); 
insertintoorders(name,itemqty,price)
  values('Naina',4,100); 
insertintoorders(name,itemqty,price)
  values('Mamta',6,2500);
insertintoorders(name,itemqty,price)
  values('Mamta',5,1500);


Simple select query
SELECT*FROMorders
Result:

But I want to result as below:

There are several ways to resolve this problem, please the below PostgreSQL statements/t-sql queries.

1- Using common table expression:


WITHcteAS (
    SELECTp.id,
           p.name,
           p.itemqty,
                             p.price,
           ROW_NUMBER()OVER(PARTITIONBYp.name
                                 ORDERBYp.priceDESC)ASrnk
      FROMordersp)
SELECTo.*
  FROMcteo
 WHEREo.rnk= 1;

Result:

 2- Using DISTINCT ON keyword


SELECTDISTINCTON (name)
       id,name,itemqty,price
FROM   orders
ORDER  BYname,priceDESC,id;

Result:

3- Using row_number() in subquery


SELECTid,name,itemqty,price
FROM   (
   SELECTid,name,itemqty,price
        ,row_number()OVER(PARTITIONBYnameORDERBYpriceDESC)ASrn
   FROM   orders
   )tmp
WHERE  rn= 1;

 Result:

4- Using array_agg() with ORDER BY


SELECT (array_agg(idORDERBYpriceDESC))[1]ASid
     ,name
     ,max(price)ASprice
FROM   orders
GROUP  BYname;





Viewing all articles
Browse latest Browse all 265

Trending Articles