Wednesday, March 7, 2012

How to do this self-join?

Greetings,

Would be thankful for your kind help. I have a table (Northwind
employees table). In the employees table, a column called ReportsTo
which lists the EmployeeID, int data type, of the manager of an
employee.This ReportsTo column is basically the EmployeeID column:

EmployeeID Title ReportsTo FirstName SecondName .....
.....
1 Manager 4 Steven Buchan
2 Sale Rep. 1 Janet Leverling
3 Clerk 1 Ropert King
4 Presedint Null Andrew Fuller

My question is how can I get the column ReportsTo to include first and
second name, instead of numbers (employeeid).

What I want is something like this(firsname, lastname OR lastname,
firstname for the ReportsTo columen):

EmployeeID Title ReportsTo FirstName SecondName
... ...
1 Manager Andrew Fuller Steven Buchan
2 Sale Rep. Steven Buchan Janet Leverling
3 Clerk Steven Buchan Ropert King
4 Presedint Null Andrew Fuller

MTIA,
Grawshagrawsha2000@.yahoo.com (al) wrote:

>EmployeeID Title ReportsTo FirstName SecondName .....
>....
> 1 Manager 4 Steven Buchan
> 2 Sale Rep. 1 Janet Leverling
> 3 Clerk 1 Ropert King
> 4 Presedint Null Andrew Fuller
>My question is how can I get the column ReportsTo to include first and
>second name, instead of numbers (employeeid).
>What I want is something like this(firsname, lastname OR lastname,
>firstname for the ReportsTo columen):
>EmployeeID Title ReportsTo FirstName SecondName
>... ...
> 1 Manager Andrew Fuller Steven Buchan
> 2 Sale Rep. Steven Buchan Janet Leverling
> 3 Clerk Steven Buchan Ropert King
> 4 Presedint Null Andrew Fuller
>MTIA,
>Grawsha

Try:
select t.employeeID, t.title, r.firstname+' '+r.lastname as 'Boss',
t.firstname, t.lastname
from testjoin t left outer join testjoin r
on t.reportsto = r.employeeID
order by t.employeeID

HTH,
Myron

No comments:

Post a Comment