@@ -106,3 +106,44 @@ select 1 as salary, 'Hello' as message
106106UNION
107107select 'Shashank' as name;
108108
109+ --- Common table expression
110+
111+ create table amazon_employees(
112+ emp_id int,
113+ emp_name varchar(20),
114+ dept_id int,
115+ salary int
116+
117+ );
118+
119+ insert into amazon_employees values(1,'Shashank', 100, 10000);
120+ insert into amazon_employees values(2,'Rahul', 100, 20000);
121+ insert into amazon_employees values(3,'Amit', 101, 15000);
122+ insert into amazon_employees values(4,'Mohit', 101, 17000);
123+ insert into amazon_employees values(5,'Nikhil', 102, 30000);
124+
125+ create table department
126+ (
127+ dept_id int,
128+ dept_name varchar(20)
129+ );
130+
131+ insert into department values(100, 'Software');
132+ insert into department values(101, 'HR');
133+ insert into department values(102, 'IT');
134+ insert into department values(103, 'Finance');
135+
136+ --- Write a query to print the name of department along with the total salary paid in each department
137+ --- Normal approach
138+ select d.dept_name, tmp.total_salary
139+ from (select dept_id , sum(salary) as total_salary from amazon_employees group by dept_id) tmp
140+ inner join department d on tmp.dept_id = d.dept_id;
141+
142+ --- how to do it using with clause??
143+ with dept_wise_salary as (select dept_id , sum(salary) as total_salary from amazon_employees group by dept_id)
144+
145+ select d.dept_name, tmp.total_salary
146+ from dept_wise_salary tmp
147+ inner join department d on tmp.dept_id = d.dept_id;
148+
149+ select * from dept_wise_salary;
0 commit comments