13. Group By

  • Used to group result set by one or more columns.
  • Query will group all rows that have the same value(s) in the specified column(s), and then apply aggregate functions to the grouped data. 
  • It is typically used in combination with aggregate functions( such as COUNT, SUM< AVG, MAX, MIN) to produce summary reports. 
Syntax      
         SELECT column1, aggregate_function(column2)
         FROM table_name GROUP BY column1;

            E.g.

                SELECT department, SUM(salary)
                FROM employees
                GROUP BY department;


                SELECT customer_id, YEAR(order_date) AS year,
                MONTH(order_date) AS month, SUM(total_amount) 
                AS total FROM orders
                GROUP BY customer_id, YEAR(order_date),
                MONTH(order_date);

                SELECT customer_id, SUM(total_amount) AS total
                FROM orders
                GROUP BY customer_id
                HAVING SUM(total_amount) > 100;


Notes:
  • All non-aggregated columns in the SELECT statement must be included in the GROUP BY clause: Any columns that are not included in the GROUP BY clause and are not aggregated using an aggregate function will cause an error or produce unexpected results.
  • Simply if you have included any column in select which are not using aggregate function you must put that column in GROUP BY  clause as well. But don't put aggregate function in GROUP BY clause 
  • The result set will be grouped first by the first column listed in the GROUP BY clause, then by the second column and so on. 

Comments