Sure, you can get the sum for every distinct value in another column using the
GROUP BY clause and the SUM() function. The syntax is as follows:
SQL
SELECT distinct_column_name, SUM(column_name)
FROM table_name
GROUP BY distinct_column_name;
For example, if you have a table called products with the columns
name and price, you could use the following SQL statement to get the sum of all product prices for each unique product name:
SQL
SELECT name, SUM(price)
FROM products
GROUP BY name;
This would return a table with two columns: name and sum. The
name column would contain the unique product names, and the sum column would contain the sum of all product prices for each unique product name.
Here is an example of how to get the sum for every distinct value in another column in MySQL:
SQL
CREATE TABLE products (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
price INT NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO products (name, price) VALUES
('Product 1', 100),
('Product 2', 200),
('Product 3', 300),
('Product 1', 400),
('Product 2', 500);
SELECT name, SUM(price)
FROM products
GROUP BY name;
This will return the following result:
name | sum
------+-----
Product 1 | 500
Product 2 | 700
Product 3 | 300
As you can see, the GROUP BY clause has grouped the rows in the
products table by the name column. The SUM() function has then been used to calculate the sum of all product prices for each unique product name.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, you can get the sum for every distinct value in another column using the
GROUP BYclause and theSUM()function. The syntax is as follows:SQL
For example, if you have a table called
productswith the columnsnameandprice, you could use the following SQL statement to get the sum of all product prices for each unique product name:SQL
This would return a table with two columns:
nameandsum. Thenamecolumn would contain the unique product names, and thesumcolumn would contain the sum of all product prices for each unique product name.Here is an example of how to get the sum for every distinct value in another column in MySQL:
SQL
This will return the following result:
As you can see, the
GROUP BYclause has grouped the rows in theproductstable by thenamecolumn. TheSUM()function has then been used to calculate the sum of all product prices for each unique product name.