选择具有关联值

时间:2017-02-10 22:58:12

标签: mysql sql max

我有两张桌子。一个是基本的客户信息,一个是订购信息。

我正在尝试找到订单状态为'placement'or'cancelled'的最大订单日期(订单日期)。如果放置或取消状态,我不在乎。我只想要最近的订单。

第一个表(信息)

 CustomerID     LAST NAME   FIRST NAME
        1              AB          BOB  
        2              BC          ROBERT
        3              AA          JOHN

第二张表(订单)

CustomerID     Order Date   Order Status
1              12/16/2016   placed
2              8/5/2016     cancelled
1              5/8/2015     cancelled
2              8/9/2016     placed
3              7/15/2016    cancelled
3              8/20/2015    placed

我希望结果是:

CustomerID  FirstName  LastName    OrderDate    OrderStatus
1              AB       BOB        12/16/2016    placed
2              BA       ROBERT     8/9/2016      placed
3              AA       JOHN       7/15/2016     cancelled

这是我的SQL语法

SELECT distinct Info.CustomerID, Info.Lastname,Info.Firstname
    FROM INFO
    INNER JOIN
    (SELECT
    order.CustomerID, LastOrderDate=max(OrderDate),order.OrderStatus
    FROM Order
    GROUP BY order.CustomerID, order.orderstatus)a
    ON a.CustomerID=Info.CustomerID

这不起作用,因为它按订单状态分组,它给出了每个所有订单状态的最大日期。然后我试了

SELECT distinct Info.CustomerID, Info.Lastname,Info.Firstname, Order.OrderStatus
    FROM INFO, Order
    INNER JOIN
    (SELECT
    order.CustomerID, LastOrderDate=max(OrderDate)
    FROM Order
    GROUP BY order.CustomerID)a
    ON a.CustomerID=Info.CustomerID

这不起作用,因为它说无法绑定Info.CustomerID。

有什么帮助吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试以下查询:

SELECT c.customerid, c.last_name, c.first_name, o.order_status, MAX(order_date)
FROM customer c JOIN order ON c.customerid = o.customerid
WHERE o.order_status IN ('placed', 'cancelled')
GROUP BY c.customerid, c.last_name, c.first_name, o.order_status;

<强>更新

如果您不希望订单状态为max日期,则可以将其从group by中删除,例如:

SELECT c.customerid, c.last_name, c.first_name, MAX(order_date)
FROM customer c JOIN order ON c.customerid = o.customerid
WHERE o.order_status IN ('placed', 'cancelled')
GROUP BY c.customerid, c.last_name, c.first_name;

另一次更新

如果在同一天下订单并取消订单,以下查询将返回两条记录:

SELECT c.customerid, c.first_name, c.last_name, o.order_date, o.order_status
FROM customer c JOIN
(SELECT o1.customerid, o1.order_date, o1.order_status
FROM `order` o1 JOIN
(SELECT o.customerid, max(o.order_date) as max_date
FROM `order` o
WHERE o.order_status in ('placed', 'cancelled')
GROUP BY o.customerid) o2
ON o1.customerid = o2.customerid and o1.order_date = o2.max_date) o
ON c.customerid = o.customerid;

这里是 SQL Fiddle