tags:

views:

73

answers:

3
person_id | manager_id | name |
          |            |      |
-------------------------------

I have to display name of every person with manager name.

Yes its complete table. Thats all I have.

+4  A: 

Which SQL dialect? Here's some TSQL, but I'm vague to the actual question ("every person with manager name"); if you mean "given a manager name, list the people (reports)", then:

SELECT peon.[person_id], peon.[name]
FROM [thetable] mgr
INNER JOIN [thetable] peon
  ON peon.manager_id = mgr.[person_id]
WHERE mgr.[name] = @name
ORDER BY peon.[name]

If you mean "list the people, along with their manager's name", then:

SELECT peon.[person_id], peon.[name], mgr.[name] AS [manager]
FROM [thetable] peon
LEFT OUTER JOIN [thetable] mgr
  ON mgr.[person_id] = peon.manager_id
ORDER BY peon.[name]
Marc Gravell
+1 Rename `mgr` to `raider` and this is the right answer!
Andomar
Good -)
stakx
No, it should be `mrg` not `mgr` because this is TQSL, not T-SQL. ;)
Mark Byers
@Mark - everyone's a critic!
Marc Gravell
+5  A: 

This one should give you all employees that have a manager, with employee_name and manager_name. Replace your_table by your table name.

If you want to get all persons, also that without manager, replace the JOIN by a LEFT JOIN. This would return NULL as manager_name for all persons without manager_id.

SELECT t1.name employee_name, t2.name manager_name
FROM [your_table] t1
JOIN [your_table] t2 ON ( t1.manager_id = t2.person_id )
Peter Lang
A: 
SELECT person.name, manager.name 
FROM table person, table manager 
WHERE person.manager_id = manager.person_id
Felix Kling
-1 for old style JOIN
gbn
@gbn: It is called *implicit join notation* not "old style JOIN". Is it forbidden to use it? Or why is it bad?
Felix Kling
works nevertheless!
AJ
@Felix: It was replaced in ANSI 92 by explicit JOIN. Also, that outer join syntax is being removed in SQL Server 2008 R2. Finally, and more practically, it mixes up filters and joins, and makes it easy to end up with partial cross joins. if you can find any references that suggest using this syntax over explicit JOIN, feel free to share them. @Ankit: So what. It's bad practice.
gbn