1

I have a table employees which has this structure:

ID | firstName | lastName | reportsTo | jobTitle |
--------------------------------------------------

I want to do a single query, which will show me firstName, lastName of employee and which employee He/She does report to (in this column, it contain ID of the employee).

So example of table data:

ID | firstName | lastName | reportsTo | jobTitle   |
----------------------------------------------------
35 | John      | Green    | 36        | TeamLeader |
----------------------------------------------------
36 | Annie     | Red      | null        | Supervisor |
----------------------------------------------------

So John Green has ID 35 and he reports to Annie Red. How to do this in a query?

So far I have come with basic:

SELECT ID, firstName, lastName from employees;

Thanks

3 Answers 3

2

Try with a subquery

SELECT ID, firstName, lastName,
( 
    SELECT a.firstName
    FROM employees a
    WHERE a.ID = reportsTo
) as report
from employees;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for quick answer unfortunately. The one below is right, this puts null everywhere in report column.
0
SELECT e.ID, e.firstName, e.lastName,ee.firstName, ee.lastName from employees e
JOIN employees ee
ON e.reportsTo=ee.ID

The name of the employee and the name which he reports to.

Comments

0

Use

SELECT A.firstName, A.lastName, B.firstName 'reports to first name', 
B.lastName 'reports to last name'
from employees A JOIN employees B
ON B.ID = A.reportsTo

You can check it here http://sqlfiddle.com/#!2/22e33f/3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.