@muriel.schmidt
To use the GROUP BY
clause to sum values in MySQL, you can follow these steps:
- Start by writing a basic SELECT statement that retrieves the data you want to work with. For example, assume you have a table called sales with columns product and amount_sold. To sum the amount sold for each product, you can use:
1
2
|
SELECT product, amount_sold
FROM sales;
|
- Add the GROUP BY clause at the end of the query, specifying the column you want to group by. In this case, you want to group by the product column:
1
2
3
|
SELECT product, amount_sold
FROM sales
GROUP BY product;
|
- Finally, apply an aggregate function, such as SUM(), to the column you want to sum the values of. In this case, you want to sum the amount_sold column:
1
2
3
|
SELECT product, SUM(amount_sold)
FROM sales
GROUP BY product;
|
This query will return the sum of the amount_sold
for each unique product
in the sales
table.