问题
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!
回答1:
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
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/9199945/mysql-query-with-group-by