Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the first matching row

Tags:

sql

ms-access

I have a table "tbl" which looks like this:

prod | cust | qty
p1   | c1   | 5
p1   | c2   | 10
p2   | c1   | 2
p3   | c2   | 8

What I need is a distinct list of product and customer pairs but only the first customer if the product is sold to more than one customer. In order words the results need to look like this:

prod | cust
p1   | c1   
p2   | c1   
p3   | c2   

I've tried this every which way I can think of but I can't quite get the correct result. Clearly neither distinct nor group by will work (on their own) since they will both return the p1, c2 row.

I found this question which is a very close match but I can't figure out how to re-write it to get it to do what I need.

To top it all this currently needs to work in Access 2007 or later but at some future point it'll need to work in MySQL as well.

Extra credit to anyone who also joins the results to the customer table so that I can look up the human readable name from the customer code e.g. c1 => Fred Bloggs Spanners

like image 628
wobblycogs Avatar asked Feb 29 '12 18:02

wobblycogs


People also ask

How do I get the first row of a selection?

To return only the first row that matches your SELECT query, you need to add the LIMIT clause to your SELECT statement. The LIMIT clause is used to control the number of rows returned by your query.

How do I select the first row in a group in SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).


1 Answers

Core Question:

SELECT prod, MIN(cust)
FROM yourTable
GROUP BY prod

For the "Bonus":

SELECT T.prod,
       T.cust,
       YC.SomeCustomerAttribute1,
       YC.SomeCustomerAttribute2
FROM (
      SELECT prod, MIN(cust) AS first_cust
      FROM yourProducts
      GROUP BY prod
) AS T
JOIN yourCustomers AS YC ON YC.cust = T.first_cust
like image 156
J Cooper Avatar answered Oct 25 '22 08:10

J Cooper