0

I have played around with many different queries, but haven't been able to locate the right syntax for this project.. I really hope someone can make sense of my mess.

I have a table with orders, one row per order, and each row containing info such as the customer number, PO#, and date of the order. A PO number can be tied to one or more orders, which is where I am getting lost. I am trying to create a query that will produce a single row containing the customer number, PO#, date of the earliest order, and date of the last order, grouped by the PO#.

Any pointers in the right direction will by much appreciated!

2
  • 1
    Which PO# do you want? That of the earliest order? That of the last order? Something else? Commented Feb 8, 2012 at 19:20
  • Do all rows with same PO have the same CustomerNumber too? Commented Feb 8, 2012 at 19:21

3 Answers 3

2

This will get the order and range stuff...

select
      o.PONumber,
      o.CustomerID,
      count(*) as TotalOrders,
      min( o.OrderID ) as FirstOrder,
      min( o.OrderDate) as FirstOrderDate,
      max( o.OrderID ) as LastOrder,
      max( o.OrderDate) as LastOrderDate
   from
      Orders o
   group by
      o.PONumber,
      o.CustomerID
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

SELECT
    o1.`customer_number` as 'customer',
    o1.`po` as 'po_number',
    (
        SELECT
            MIN(`date`)
        FROM
            `orders`
        WHERE
            `id` = o1.`id`
    ) as 'earliest_date'
FROM
    `orders` o1
GROUP BY
    o1.`po`

Hope that helps.

1 Comment

by doing a sub-select as a column will be a big performance hit, especially on larger tables. It requires each SELECT MIN() to be called for every ID vs using the standard MIN() / MAX() across all the qualified records. You have the group by which results the same one record per P/O
0
SELECT o.custumer, o.po_number, o.order_count, max.max_date, min.min_date
FROM
(
SELECT o.'costumer_number' as 'custumer', o.'po' as 'po_number', count('order_number') as 'order_count'
FROM 'orders' o
GROUP BY o.'costumer_number', o.'po'
) o
INNER JOIN (
    SELECT o.'costumer_number' as 'custumer', o.'po' as 'po_number', MAX('order_date') as 'max_date'
    FROM 'orders' o
    GROUP BY o.'costumer_number', o.'po'    
) max ON o.'customrer' = max.'costumer' and o.'po_number' = max.'po_number'
INNER JOIN (
    SELECT o.'costumer_number' as 'custumer', o.'po' as 'po_number', min('order_date') as 'min_date'
    FROM 'orders' o
    GROUP BY o.'costumer_number', o.'po'    
) min ON o.'customrer' = min.'costumer' and o.'po_number' = min.'po_number'
ORDER BY 1,2

That shold clear it out

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.