SQL group byIn SQL, The Group By statement is used for organizing similar data into groups. The data is further organized with the help of equivalent function. It means, if different rows in a precise column have the same values, it will arrange those rows in a group.
Syntax:Sample Table:Employee
Student
Example:Group By single column: Group By single column is used to place all the rows with the same value. These values are of that specified column in one group. It signifies that all rows will put an equal amount through a single column, which is of one appropriate column in one group. Consider the below query: The output of the query is:
In the output, the rows which hold duplicate NAME are grouped under a similar NAME, and their corresponding SALARY is the sum of the SALARY of the duplicate rows.
Consider the below query: Output:
In the above output, the student with similar SUBJECT and YEAR are grouped in the same place. The students who have only one thing in common belongs to different groups. For example, if the NAME is same and the YEAR is different. Now, we have to group the table according to more than one column or two columns. HAVING Clause WHERE clause is used for deciding purpose. It is used to place conditions on the columns to determine the part of the last result-set of the group. Here, we are not required to use the combined functions like COUNT (), SUM (), etc. with the WHERE clause. After that, we need to use a HAVING clause. Having clause Syntax:Example:Output:
According to the above output, only one name in the NAME column has been listed in the result because there is only one data in the database whose sum of salary is more than 50000. It should be placed on groups, not on the columns. Points:
Next TopicSQL Tutorial |