Im working on a SQL query to calculate the total quantity of products ordered by each customer. The goal is to return the sum of ordered quantities per unique customer, along with the customer's ID, and label the sum as "Total Ordered".
Here's the structure of my dbo.ProductOrders table:
CREATE TABLE dbo.ProductOrders (
POID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
ProductId INT NOT NULL,
CustomerId INT NOT NULL,
OrderedQuantity INT,
-- Additional fields...
);
-- Sample data insertion
My current query is:
SELECT CustomerId, OrderedQuantity
FROM dbo.ProductOrders;
This query lists all the orders, including multiple occurrences of the same customer IDs with different order quantities. How can I modify this query to show only unique customer IDs with their total ordered quantities summed up?
What is the correct SQL syntax to aggregate the total quantities for each unique customer?
Is there a specific function or technique in SQL for summing up values grouped by a unique identifier?
I'm specifically struggling with the aggregation and grouping part of the query.
Just group by
and sum
:
select customerID, sum(OrderedQuantity) total_ordered
from productOrders
group by customerID