Database Group by & Having Clause

← Go back to Database Chapter



Group By

The Group by clause is used to divide the table into multiple groups based on the specified columns.

Having

The having clause is used to specify the condition placed on the groups.

Example:

groupby and having class example in java

Question 1: Display the total fee collected.
Answer: Select sum (fee paid) from students;

groupby and having class example in java

Question 2: Display the total fee collected from the Madiwala branch.
Answer: Select sum (fee paid) from students where branch = 'madiwala'

groupby and having class example in java

Question 3: Display the branch wise collection in the following formats:

KarveNagar 20000
Madiwala 28000
Macerthali 12000
Answer: Select sum (fee paid) from student group by branch;
groupby and having class example in java

Question 4: Select branch, sum (fee paid) from student group by branch.
Answer:

groupby and having class example in java

Question 5: Select branch as "Branch Name", sum (fee paid) "Total collection" from student group by branch.
Answer:

groupby and having class example in java

Question 6: Display the fee collected from KarveNagar and Madiwala branch.
Answer:
Select sum ( Fee paid) from students where branch in ('madiwala', 'KarveNagar');
(or)
Select branch as "Branch Name", sum (fee paid) "Total collection" from student group by branch having branch in ('madiwala', 'KarveNagar');

groupby and having class example in java

Question 7: Display the city wise fee balances in the following format:

City Name Total Balance
KarveNagar 20000
Madiwala 28000
Macerthali 12000
Answer:
Select city as "City Name ", Sum (fee paid) as "Total Balance" from student group by city;
groupby and having class example in java

Question 8: Display city as "City Name" sum (fee balance) as "Total Balance " from student group by city.
Answer:

groupby and having class example in java