SQL Query to get desire output-4

SQL Query to get desire output-4

Lets say we have tow tables named with Employee and Department shown as below:

SQL Query to get desire output-4 Tables
SQL Query to get desire output-4 Tables

Now if we want Total salary and Average salary of Department wise shown as below:

SQL Query to get desire output-4-query-1
SQL Query to get desire output-4-query-1

For that we have to write query as below:

CREATE TABLE #employee (emp_id int, emp_name varchar(10),dept_id int ,salary float)

INSERT INTO #employee
SELECT 1,'A',null,2000
UNION 
SELECT 2,'B',1,4000
UNION 
SELECT 3,'C',1,2000
UNION 
SELECT 4,'D',3,3000

CREATE TABLE #Department (dept_id int,dept_name varchar(100))
INSERT INTO #Department
SELECT 1,'ASP .NET'
UNION
SELECT 2,'SQL'
UNION
SELECT 3,'PHP'

SELECT * FROM #employee
SELECT * FROM #Department

SELECT dept.dept_name,SUM(emp.salary) as TotalSalary,AVG(emp.salary) AverageSalary  FROM #employee emp 
RIGHT JOIN #Department dept
ON emp.dept_id=dept.dept_id
GROUP BY dept.dept_name
 
DROP TABLE #employee
DROP TABLE #Department

 

Leave a Reply