falias
falias

Reputation: 51

Select row from earliest date

i need a list from all products that contains 2 columns with the date the product was first ordered and the ordered quantity of this product.

Structure:
tbl_product
- productID
- productName

tbl_orderProduct
- orderProductID
- orderID
- productID
- quantity

tbl_order
- orderID
- orderedDate

SELECT p.productName, firstOrder.orderedDate FROM tbl_product p
LEFT JOIN(
    SELECT op.productID, MIN(o.orderedDate) AS orderedDate FROM tbl_orderProduct op
    JOIN tbl_order o ON op.orderID = o.orderID
    GROUP BY op.productID
)
firstOrder ON firstOrder.productID = p.productID

My first attempt to retrieve the date works so far but i can't figure out how to get the quantity because i have to get the Order and then go back to tbl_orderProduct for the quantity.
I don't want to get the order by select via the firstOrder.ordererdDate because there's a chance that it's not unique.

Also i can't pass the orderID it with the select in my 'Left Join' because i also have to add it in the 'Group By' then and it would return a row for every order that contains the product. So somehow i have to retrieve the orderID or the orderProductID from the First Order.

Thanks in advance!

Upvotes: 0

Views: 189

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

Assuming you're using at least SQL-Server2005, you can use a common-table-expression with ROW_NUMBER function:

WITH CTE AS
(
   SELECT p.productName, o.orderedDate, quantity
   , RN = ROW_NUMBER() OVER ( PARTITION BY p.productID ORDER BY o.orderedDate )
   FROM tbl_product p 
   INNER JOIN tbl_orderProduct op ON p.productID=op.productID
   INNER JOIN tbl_order o ON op.orderID=o.orderID
)
SELECT * FROM CTE WHERE RN = 1

Upvotes: 0

Related Questions