带分组的MySQL查询

时间:2012-02-08 19:19:33

标签: mysql group-by

我玩了很多不同的查询,但是找不到这个项目的正确语法..我真的希望有人能理解我的混乱。

我有一个订单表,每个订单一行,每行包含客户编号,PO#和订单日期等信息。 PO编号可以绑定到一个或多个订单,这是我迷路的地方。我正在尝试创建一个查询,该查询将生成一个包含客户编号,PO#,最早订单日期和最后订单日期的行,按PO#分组。

任何指向正确方向的人都会非常感激!

3 个答案:

答案 0 :(得分:2)

这将获得订单和范围......

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

答案 1 :(得分:0)

试试这个:

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`

希望有所帮助。

答案 2 :(得分: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

那应该清除它