Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

GROUP BY



The SQL GROUP BY Statement


The SQL GROUP BY statement is used to group rows that have the same values into summary rows, typically to apply aggregate functions like COUNT, SUM, AVG, MAX, or MIN to each group. It is often used in combination with aggregate functions to perform calculations on each group separately. The basic syntax of the GROUP BY statement is as follows:

SELECT column1, column2, ..., aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;


For example, let's say you have a table called orders with columns customer_id and total_amount. If you want to calculate the total amount spent by each customer, you can use the GROUP BY statement like this:

SELECT customer_id, SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id;

In this example:

The result will contain each customer_id along with the corresponding total amount spent by that customer.

Remember that when you use a GROUP BY statement, all selected columns must either be listed in the GROUP BY clause or be arguments of aggregate functions. Otherwise, most SQL databases will throw an error.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java