INNER JOIN using GROUP BY clause
Using GROUP BY with INNER JOIN allows grouping the result set by one or more columns after combining rows from multiple tables. This is often used with aggregate functions like SUM(), COUNT(), and AVG() to produce summarized insights from related tables.
SELECT T1.ID,
T1.NAME,
SUM(T1.TEAM) AS EMPCOUNT
FROM EmployeeName T1
INNER JOIN Position T2
ON T1.ID = T2.ID
GROUP BY T1.ID
ORDER BY T1.ID, T2.TITLE;
Result Comparison:
Without GROUP BY clause:
ID NAME EMPCOUNT
20 Sam 5
30 Cindy 10
30 Cindy 2
With GROUP BY clause:
ID NAME EMPCOUNT
20 Sam 5
30 Cindy 12
INNER JOIN with Multiple Tables
Scenario: Analyze employee performance and satisfaction across departments, projects, and managers.
Tables Involved:
- employees (employeeID, name, departmentID, managerID)
- departments (departmentID, name)
- projects (projectID, name, managerID)
- performance_reviews (employeeID, rating)
- satisfaction_surveys (employeeID, satisfaction_score)
SELECT
employees.name AS employee_name,
departments.name AS department,
projects.name AS project,
performance_reviews.rating,
satisfaction_surveys.satisfaction_score
FROM employees
INNER JOIN departments
ON employees.departmentID = departments.departmentID
INNER JOIN projects
ON employees.employeeID = projects.managerID
INNER JOIN performance_reviews
ON employees.employeeID = performance_reviews.employeeID
INNER JOIN satisfaction_surveys
ON employees.employeeID = satisfaction_surveys.employeeID
WHERE departments.name = 'Sales';
INNER JOIN with GROUP BY for Sales Analysis
Scenario: Identify top-selling products across different stores along with supplier and stock information.
Tables Involved:
- products (productID, name, supplierID)
- suppliers (supplierID, name)
- stores (storeID, name)
- sales (productID, storeID, quantity_sold)
- inventory (productID, storeID, quantity_in_stock)
SELECT
products.name AS product_name,
suppliers.name AS supplier,
stores.name AS store,
SUM(sales.quantity_sold) AS total_sales,
SUM(inventory.quantity_in_stock) AS current_stock
FROM products
INNER JOIN suppliers
ON products.supplierID = suppliers.supplierID
INNER JOIN sales
ON products.productID = sales.productID
INNER JOIN stores
ON sales.storeID = stores.storeID
INNER JOIN inventory
ON products.productID = inventory.productID
AND stores.storeID = inventory.storeID
WHERE suppliers.name = 'Acme Inc.'
GROUP BY product_name, supplier, store
ORDER BY total_sales DESC;