我想创建一个返回客户最新销售订单的查询。
我有一个Customer和一个Orders表,它们在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
答案 0 :(得分:0)
尝试在创建的订单上放置MAX。按客户ID分组。 (错字)
PS:我在移动设备上。没有代码片段格式。
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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