0

Here is the given question:

Show me a list of the product codes along with the number of times that each code has been ordered (note, order quantity does affect the number of total times ordered); only include product codes that have been ordered at least once?

I have tried the following

SELECT DISTINCT productId, orderQuantity 
FROM Order
WHERE (orderQuantity > 0);

The table comes up with duplicate product ids. How do I get a table of distinct product ids with the SUM of their order quantities?

4

1 回答 1

4

I think this is what you're looking for:

SELECT productID, SUM(orderQuantity)
FROM Order
WHERE orderQuantity > 0
GROUP BY productID

You have to use an aggregate function, in this case SUM(), to have the sum of your quantities and you want the sums to be grouped by each product, in your case productID.

To understand how this works, just try removing the GROUP BY statement and the productID from the SELECT statement and the query will return the SUM of all quantities.

SELECT SUM(orderQuantity)
FROM Order
WHERE orderQuantity > 0

Then, if you add just the GROUP BY productID you will get the sum of quantities ordered for each product.

SELECT SUM(orderQuantity)
FROM Order
WHERE orderQuantity > 0
GROUP BY productID

Then just add the productID back in the SELECT statement to understand the information displayed.

于 2013-10-03T08:51:21.810 回答