Tags
Asked 2 years ago
12 May 2021
Views 139
Arnaldo

Arnaldo posted

Can we use where group by together?

Can we use where group by together?
sandip

sandip
answered Jun 23 '23 00:00

WHERE and GROUP BY together in MySQL, you can filter the rows before grouping them based on specific conditions. Here's an example that demonstrates their combined usage:

Let's say we have a table called orders with columns order_id, customer_id, and order_total, and we want to retrieve the total order amount for each customer but only for orders with a total greater than $100.

Here's the query that combines WHERE and GROUP BY clauses:


SELECT customer_id, SUM(order_total) AS total_amount
FROM orders
WHERE order_total > 100
GROUP BY customer_id;

In this example, the WHERE clause filters the rows by specifying the condition order_total > 100, which ensures that only orders with a total greater than $100 are included in the calculation. Then, the GROUP BY clause groups the filtered rows based on the customer_id column.

The SELECT statement retrieves the customer_id and calculates the sum of the order_total for each customer using the SUM() function. The AS total_amount part assigns an alias to the calculated sum for readability.
Post Answer