我有一个表Customers
与CustomerID
和PhoneNumber
,第二个表是Orders
,CustomerId
和OrderNumber
和第三个已OrderDetails
,OrderNumber
和PriceOfOneUnit
的表格UnitsOrdered
。我需要为放置最大订单(PhoneNumber
)的客户找到PriceOfOneUnit * UnitsOrdered
。在加入3个表后,将count(PriceOfOneUnit*UnitsOrdered)
作为A1
然后再按“按客户编号顺序排序”A1 DESC LIMIT 1显然不起作用。任何人都可以提供帮助。
答案 0 :(得分:0)
如果我们接受你的话,你想要的是最大的单一项目而不是最大的订单,你可以找到最大的项目,然后找到它所属的订单,然后是客户谁下订单。您可以使用虚拟聚合函数从orderDetails中撤回订单ID。
编辑: 好的,对于刚开始的人,我认为用维恩图来思考并使用所谓的内联视图和子查询可以更清楚:
select customername, phone
from customer
inner join
(
select o.id, customerid from orders o
inner join
(
select od.orderid from orderdetail od
where (od.qty * od.itemprice) =
(
select max(od.qty * od.itemprice)
from orderdetail as od
)
) as biggestorder
on o.id = biggestorder.orderid
) as X
on customer.id = X.customerid
括号内的每个查询都返回一个可以与其他集合连接/交叉的集合。
答案 1 :(得分:0)
尝试一下,
SELECT cus.CustomerId, cus.PhoneNumber
FROM Customers cus
INNER JOIN Orders a
ON cus.CustomerId = a.CustomerId
INNER JOIN OrderDetails b
On a.OrderNumber = b.OrderNumber
GROUP BY cus.CustomerId, cus.PhoneNumber
HAVING SUM(b.PriceOfOneUnit * b.UnitsOrdered) =
(
SELECT SUM(b.PriceOfOneUnit * b.UnitsOrdered) totalOrdersAmount
FROM Orders aa
INNER JOIN OrderDetails bb
On aa.OrderNumber = bb.OrderNumber
GROUP BY aa.CustomerId
ORDER BY totalOrdersAmount DESC
LIMIT 1
)