需要查询帮助才能返回每个人最近的订单,订单日期,订单中的产品数量和总金额。我有点想要获得产品数量和总数。
以下是表格图表
不确定我是否应该使用多个连接或子查询:
SELECT FirstName, LastName, MAX(O.OrderDate), O.OrderDate
FROM Customer C
INNER JOIN Order O ON C.CustomerID = O.CustomerID
答案 0 :(得分:0)
不确定您是否需要聚合,但在此处:
SELECT customer.firstname, customer.lastname, COUNT(DISTINCT orderitem.productid), [order].totalamount
FROM [order] LEFT JOIN customer ON [order].customerid=customer.id LEFT JOIN orderitem ON order.id=orderitem.orderid
WHERE [order].date=MAX([order].date)
GROUP BY customer.firstname,customer.lastname, [order].totalamount
仍然不知道你为什么要为最后一个订单申请一个where子句,由你决定是否保留condtion。
答案 1 :(得分:0)
从product
等假定的暗表开始,这是一个好习惯。这个查询应该有所帮助。最好汇总数量和金额以获得总体水平的结果
SELECT FirstName
,LastName
,max(o.orderdate) Orderdate
,Sum(Quantity) Quantity
,Sum(TotalAmount) TotalAmount
FROM Product p
INNER JOIN Orderitem oi
ON Oi.product_id = p.id
INNER JOIN
ORDER o
ON o.id = oi.order_id
INNER JOIN Customer c
ON c.id = o.Customer_id
GROUP BY FirstName
,LastName
答案 2 :(得分:-1)
第一。使用子查询过滤掉您需要的订单,选择每个客户的最大订单日期的orderid。
第二。从订单表中选择您需要的所有内容,然后从表订单项中加入一个包含所需分组的子查询。
这样的事情:
select o.*, oi.*
from order as o
left join (
select count(*) as oi_cnt,
sum(unitprice*quantity) as oi.sum,
order_id
from orderitem
group by order_id
) as oi
on oi.order_id = o.id
where exists
(select max(o2.orderdate) as md,
o2.customerid
from order as o2
group by o2.customerid
having o2.md = o.orderdate
and o2.customerid = o.customerid
)