1

我想做一个查询,返回客户最近的销售订单。

我有一个以 ID 连接的客户和订单表,并且我进行了以下查询以返回所有值。谁能帮我修改它以仅返回每个 ID 的最新值?Orders.created_at 的格式如下 yyyy-MM-dd HH:mm:ss

SELECT Customers.ID, Customers.Name, Customers."Sales Responsible US", Customers."Sales     Responsible", Customers."Website", ISNULL(Orders.row_invoiced, '-1'), Orders.status, Orders.created_at
FROM "Customers"
LEFT JOIN Orders
On Customers.ID=Orders.customer_id
4

4 回答 4

0

尝试将 MAX 放在创建的订单上。按客户 ID 分组。(错字)

PS:我是手机。没有代码片段格式。

于 2012-11-15T09:17:07.660 回答
0

试试这个 ::

   SELECT Customers.ID, 
Customers.Name, 
Customers."Sales Responsible US", 
Customers."Sales     Responsible", 
Customers."Website", 
IFNULL(Orders.row_invoiced, '-1'), 
Orders.status, MAX(Orders.created_at)
    FROM "Customers"
    LEFT JOIN Orders On Customers.ID=Orders.customer_id

    group by Orders.customer_id
于 2012-11-15T09:17:58.457 回答
0

我将加入您已经拥有的所有子查询,以获取max(created_at)每个客户 ( group by customer_id) 的最新 () 订单日期。

SELECT Customers.ID, 
    Customers.Name, 
    Customers."Sales Responsible US", 
    Customers."Sales     Responsible", 
    Customers."Website", 
    ISNULL(Orders.row_invoiced, '-1'), 
    Orders.status, 
    Orders.created_at
FROM "Customers"
LEFT JOIN Orders On Customers.ID=Orders.customer_id
left join (
    select customer_id, max(created_at) as created_at
    from Orders 
    group by customer_id
) as t on Orders.customer_id = t.customer_id and Orders.created_at = t.created_at
于 2012-11-15T09:18:46.183 回答
0

嗨希望这会满足你的要求

SELECT Customers.ID, Customers.Name, Customers."Sales Responsible US", Customers."Sales     Responsible", Customers."Website", ISNULL(Orders.row_invoiced, '-1'), Orders.status, MAX(Orders.created_at)
FROM "Customers"
LEFT JOIN Orders
On Customers.ID=Orders.customer_id 
GROUP BY Orders.customer_id
于 2012-11-15T09:29:34.403 回答