gpt4 book ai didi

mysql - 选择具有关联值的 MAX(日期)

转载 作者:行者123 更新时间:2023-11-29 19:25:46 25 4
gpt4 key购买 nike

我有两张 table 。一是客户基本信息,一是订购信息。

我正在尝试查找订单状态为“已下达”或“已取消”的最大(订单日期)。我不在乎状态是放置还是取消。我只想要最新的订单。

第一个表(信息)

 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 无法绑定(bind)。

有什么帮助吗?谢谢!

最佳答案

您可以尝试以下查询吗:

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;

更新

如果您不希望按订单状态显示最大日期,则可以将其从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

关于mysql - 选择具有关联值的 MAX(日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42170017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com