srik123
srik123

Reputation: 3

How to Integrate Result of 2 SQL queries of same Table in a Single Query?

I am new to SQL i have just started to learn SQL. I have an Employee table which has 3 columns :

when manager_id is same as id means an employee will have another employee as manager.

For example:

Employee "AAA" will have "BBB" as his manager if employee record has id of employee "BBB" as manager_id.

How could I write an single SQL query which would give me result of "Employee name" and their corresponding "Manager_name".

Below are the details of Table, Queries tried so far and The expected result.

Employee Table:

select * from test.employee;

enter image description here

Query 1:

SELECT name as manager_name FROM test.employee  
 where manager_id IN(select id from test.employee)
 group by manager_id;

enter image description here

Query 2:

 SELECT name as emp_name FROM test.employee

enter image description here

How could I achieve the combined result of Query 1 and Query 2 i.e as shown below:

enter image description here

Upvotes: 0

Views: 27

Answers (1)

James Z
James Z

Reputation: 12318

You need to have the same table twice and give it an alias, something like this:

SELECT e.name, m.name as manager_name
FROM test.employee e
join test.employee m on e.manager_id = m.id

If there's employees where manager doesn't exist, you might want to use left outer join instead

Upvotes: 2

Related Questions