0

我有一张Customers带有CustomerIDandPhoneNumber的桌子,第二张桌子OrdersCustomerIdandOrderNumber和第三张桌子OrderDetailsOrderNumber, PriceOfOneUnitand UnitsOrdered。我需要找到PhoneNumber最大订单的客户 ( PriceOfOneUnit * UnitsOrdered)。在加入 3 个表后,执行count(PriceOfOneUnit*UnitsOrdered)asA1然后 `Group By CustomerId Order By A1 DESC LIMIT 1 显然不起作用。任何人都可以帮忙。

4

2 回答 2

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
        )
于 2013-03-24T17:23:49.827 回答
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

括号内的每个查询都返回一个可以与其他集合连接/相交的集合。

于 2013-03-24T16:50:49.407 回答