CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

MYSQL GROUP BY and HAVING



 MySQL  GROUP BY

The GROUP BY statement in SQL is used to arrange data into groups with the help of some functions. GROUP BY statement is used to retrieve grouped records based on one or more columns.

The aggregate function on SELECT Statement can be used with the GROUP BY Statement.
Aggregate Functions : AVG(),COUNT(),MAX(),MIN(),SUM().

The syntax for GROUP BY Statement in SQL -:

SELECT  <COL_NAME>
FROM  <TABLE>
WHERE  <CONDITION>
GROUP BY <COL_NAME>
HAVING <CONDITION ON GROUPS>;

Description MySQL GROUP BY -:

The GROUP BY clause combines all those records (Rows) that have identical values in a particular field (Column) or a group of fields.
This grouping results in one summary record per group.

If you want to total salary for all employees then we used the SUM function and you will get a sum of the total salary.
group by

If you want to total salary department wise like D1 or D2 then we have used GROUP BY.
group by MYSQL

Now you have also used the SUM function and using GROUP BY  tHen you will get the department-wise total salary  You can see all D1 and D2 columns combine in one row.
group by MYSQL

GROUP BY(Nested Grouping) using more than one column -

If you want to GROUP BY using more than one column, you can give all columns by using comma separation.  

Syntex -

SELECT Col1, Col2,AGG_FUN(Col3)
FROM Tab1
[WHERE <Condition>]
GROUP BY Col1, Col2 ;

group by MYSQL Nested grouping

GROUP BY Condition -

The GROUP BY clause is used with Aggregate Functions.
 All the fields (Columns) other than used in aggregate function should be put in GROUP BY clause.

Syntex -

SELECT AGG_FUN(Col1), Col2, Col3
FROM Tab1
WHERE <Condition>
GROUP BY Col2, Col3;










No comments:

Post a Comment