Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL group by novice - help please 1

Status
Not open for further replies.

orangeseatbelt

Technical User
Dec 4, 2010
10
GB
Hi, I can create queries using the grid in Access, but I'm trying to get used to writing SQL and understand Group By queries. When a group by is very simple I can (just about) manage it, but the following problem has me beat - any help would be great.

In the following small table I can write a SQL statement to retrieve the minimum price for each custName group, BUT I also want to retrieve the ID for that minimum price - and that's when I get incorrect results.

When I write:

SELECT Min(Sales.Price), Sales.CustName
FROM Sales
GROUP BY Sales.CustName;

that works just fine. So then I think I can just modify the above statement by putting min(Sales.ID) before/after the min(Sales.Price) and although that runs - it doesn't give me the ID from the min(price) row.

thanks for reading.

ID Date Price Quantity custName
1 01-Jan-11 160 2 smith
2 02-Jan-11 190 2 johnson
3 03-Jan-11 500 5 baldwin
4 04-Jan-11 420 2 smith
5 05-Jan-11 1000 4 wood
6 06-Jan-11 820 4 smith
7 07-Jan-11 22 2 baldwin


 
Code:
SELECT t.CustName
     , t.Price
     , t.ID
     , t.Date
     , t.Quantity
  FROM ( SELECT CustName
              , Min(Price) AS min_price
           FROM Sales
         GROUP 
             BY CustName ) AS m
INNER
  JOIN Sales AS t
    ON (
       t.CustName = m.CustName
   AND t.Price = m.min_price
       )
the extra parentheses in the ON clause aren't usually required, but i think Access needs them

:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top