0

How do I get top 1 record for each product from the query below?

  SELECT DISTINCT o.product, o.orderID, od.qty, od.amount FROM
  orders o, orderdetails od WHERE o.orderID=od.orderID


Product  OrderID   Qty   Amount
Pen       11222    10     100.00
Pen       11223     5      50.00
Pen       11224     1      10.00
Book      22222     1      12.00
Book      2223      5      10.00
Scale     1111      2       9.00
Scale     2222      1       2.00  
3
  • What do you mean by the top 1 record? Do you want a distinct list of products for an order?
    – Bob
    Sep 11, 2009 at 19:13
  • I think he wants the the 'top' one of each product. I think. Sep 11, 2009 at 19:14
  • You are right George. I want top one of each product
    – acadia
    Sep 11, 2009 at 19:24

3 Answers 3

1
SELECT 
    o.Product, MAX(od.QTy) 
FROM 
    orders o
    INNER JOIN orderdetails od ON o.orderID=od.orderID
GROUP BY o.Product

or

SELECT 
    o.Product, MAX(od.Amount) 
FROM 
    orders o
    INNER JOIN orderdetails od ON o.orderID=od.orderID
GROUP BY o.Product

depending on what you consider as "top" product.

0

Top based on what? Most Quantity? if so try this

  Select * From Orders O
  Where OrderId = 
     (Select Max(orderId) From Orders
      Where product = P.product
        And Qty = (Select Max(Qty) 
                   From orders 
                   Where Product = O.Product))

Otherwise if Top means something else change last three lines to find Orderid for the record that satisfies whatever that definition of 'Top'

0

Give this a shot...

Select o.product, o.orderID, od.qty, od.amount 
from orders o, orderdetails od 
where o.orderID = od.orderID
   and o.orderID in (Select Min(o.orderId) 
                     From orders o
                     Group By o.product)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.