sql - Select first row in each GROUP BY group? -


As the title suggests, I select the first row of each group of rows grouped with a group I would like to .

Specifically, if I have a purchase table that looks like this:

  Choose from purchases;  
 id | Customer | Total --- + ---------- + ------ 1 | Joe 5 Sally | 3 3 Joe 2 4 | Sally | 1 

I want to query for the biggest purchase ( total ) for each customer for id . Something like this:

  first select (id), customer, order by total (customer) group by total DESC;  
 First (ID) | Customer | First (total) ---------- + ---------- + ------------- 1 Joe 5 Sally | 3 

Oracle 8i +, SQL Server 2005+, PostgreSQL 8.4+, db2, firebird 3.0+, On Teradata, Sybase, Vertica:

  as a summary (Selection PID, P. Customer, P. Total, ROW_NUMBER) (P. Order by P. Customer P. Total by DESC) Purchase From RP) Selection from S * Summary from where s.rk = 1  

supported by any database:

But to add logic to break the relationship Required:

  SELECT MIN (x.id), - if you If you want the highest x.customer, then connect x to x plus (max_total PURCHASES p group as SELECT p.customer, MAX) and y.customer = x.customer and y.max_total = x X.customer, x.total  
by total group

Comments