SQL join tables with group by and order by
In this page, we are going to discuss the usage of GROUP BY and ORDER BY clause within a join.
Example:
Sample table: agents
Sample table: orders
To get 'agent_code' and 'agent_name' columns from the table 'agents' and sum of 'advance_amount' column from the table 'orders' after a joining, with following conditions -
1. 'agent_code' of 'agents' and 'orders' must be same,
2. the same combination of 'agent_code' and 'agent_name' of 'agents' table must be within a group,
3. 'agent_code' of 'agents' table should arrange in an order, default is ascending order,
the following SQL statement can be used:
SELECT agents.agent_code,agents.agent_name,
SUM(orders.advance_amount)
FROM agents,orders
WHERE agents.agent_code=orders.agent_code
GROUP BY agents.agent_code,agents.agent_name
ORDER BY agents.agent_code;
Sample Output:
AGENT_CODE AGENT_NAME SUM(ORDERS.ADVANCE_AMOUNT) ---------- ---------------------------------------- -------------------------- A001 Subbarao 200 A002 Mukesh 3500 A003 Alex 1000 A004 Ivan 2100 A005 Anderson 3100 A006 McDen 600 A007 Ramasundar 500 A008 Alford 3300 A009 Benjamin 100 A010 Santakumar 3700 A011 Ravi Kumar 900 A012 Lucida 450
Here is a new document which is a collection of questions with short and simple answers, useful for learning SQL as well as for interviews.
Check out our 1000+ SQL Exercises with solution and explanation to improve your skills.
Previous: Joining tables through referential integrity
Next: Join two tables related by a single column primary key or foriegn key pair
SQL: Tips of the Day
What is the most efficient/elegant way to parse a flat table into a tree?
WITH RECURSIVE MyTree AS ( SELECT * FROM MyTable WHERE ParentId IS NULL UNION ALL SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id ) SELECT * FROM MyTree;
Ref: https://bit.ly/3FPYFFF
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook