简体   繁体   中英

SQL How to SUM up the total Quantity

1.The customer id, company name, number of orders, and total order amount for all customers who purchased an item in the Beverages category.

SELECT Customers.CustomerID, Customers.CompanyName, Categories.CategoryName, [Order Details].Quantity
FROM Customers, Categories, [Order Details]
WHERE Categories.CategoryName ='Beverages';

Then a new query

2.Same as problem 1 but, limit the list to all customers who placed 3 or more orders. Do I use the =>3 command ?

This question might sound simple, but we need to get the customers who placed more that 3 orders first before joining other tables.

select t1.CustomerID
    , t1.CompanyName
    , t3.CategoryName
    , t4. Quantity
from Customers t1
inner join 
    (select customerId from 
    [Order Details]
    where categoryId = (select categoryId from Categories where CategoryName ='Beverages')
    group by customerId
    having count(1) >= 3) t2 on t2.CustomerID = t1.customerId
inner join [Order Details] t4 on t4.CustomerID = t1.customerId
inner join Categories t3 on t3.CategoryId = t4.CategoryId
 where t3.CategoryName ='Beverages'

Try this query.

SELECT t1.CustomerID
    , t1.CompanyName
    , t3.Categoryname
    , t4. Quantity,noorders
FROM Customers t1
INNER JOIN [Order Details] t4 ON t4.CustomerID = t1.customerId
INNER JOIN Categories t3 ON t3.CategoryId = t4.CategoryId
CROSS APPLY (SELECT noorders=count(orderid) FROM [Order Details] ord2 
        WHERE ord2.CustomerID=t4.CustomerID and ord2.CategoryId = t3.CategoryId) AS t2
 WHERE t3.CategoryName ='Beverages'
 and t2.noorders>=3

This is what final work for me

SELECT Customers.CustomerID, Customers.CompanyName, Categories.CategoryName,
Sum([Order Details].Quantity) as TotalOrders, Count (Orders.OrderID)
FROM Customers, Categories, [Order Details], Orders
WHERE Categories.CategoryName ='Beverages'
group by [Order Details].Quantity, Customers.CustomerID, Customers.CompanyName, Categories.CategoryName
Having Count (Orders.OrderID) >=3;

Thank you all for the help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM