大多数客户订购大多数产品以及他们订购的产品名称和客户名称和金额

时间:2015-07-09 15:54:27

标签: sql

这是包含记录内容的表

Customers      91
Employees      10
OrderDetails  518
Orders        196
Products       77
Shippers        3
Suppliers      29

这是我想的sql查询,但我不确定我是否得到了正确的结果我需要帮助

Select customername, productname, Sum(price * quantity) as price, max (quantity) as Qantity_ordered
From customers
Inner join orders
   On  customers.customerId = orders.customerid
Inner Join Orderdetails
    On orders.orderid = orderdetails.orderid
Inner Join Products
    On orderdetails.productid = products.productid
;

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你需要以下声明:

Select customername, 
    productname, 
    max(Temp.price) as price,
    Temp.quantity as Qantity_ordered
FROM
(Select customerid, productid, Sum(price * quantity) as price, max (quantity) as Qantity_ordered
    From customers
    Inner join orders
    On  customers.customerId = orders.customerid
    Inner Join Orderdetails
    On orders.orderid = orderdetails.orderid
    Inner Join Products
    On orderdetails.productid = products.productid
    Group By customerid, productid) Temp
Inner Join customers 
On customerId = Temp.customerId
Inner join orders
On  Temp.customerId = orders.customerid
Inner Join Orderdetails
On orders.orderid = orderdetails.orderid
Inner Join Products p
On  p.productid = Temp.productid
where quantity = Temp.Qantity_ordered
Group By customername, 
   productname, 
   Temp.quantity