How To Use Self Join In Sql Server 2000 2005
- Get link
- X
- Other Apps
For self join in sql you can try the following example:
Create table employees:
emp_id | emp_name | emp_manager_id |
1 | John | Null |
2 | Tom | 1 |
3 | Smith | 1 |
4 | Albert | 2 |
5 | David | 2 |
6 | Murphy | 5 |
7 | Petra | 5 |
Now to get the names of managers from the above single table you can use sub queries or simply the self join.
Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id
Result:
manager | employee |
John | Tom |
John | Smith |
Tom | Albert |
Tom | David |
David | Murphy |
David | Petra |
Understanding the Self Join Example
In the above self join query, employees table is joined with itself using table aliases e1 and e2. This creates the two views of a single table.
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id
Here e.emp_manager_id passes the manager id from the 2nd view to the first aliased e1 table to get the names of managers.
- Get link
- X
- Other Apps
Comments
i m too happy, thank u very much.
Good explaination.
Deepak patil
so use full for learner....
kindly reply soon...
I need it urgent
Your scenario may be invalid since a manager cannot be a self reporting manager but even then it filters out if you use the same query
Empid Fname Lname Mgrid
1 x Last x
2 First x 1
Want to join and the result should be like "First Last" in one row
Written a query like,
"Select A.Fname, B.Lname
From Emp A join Emp B
on A.Mgrid = B.Empid"
but getting the result with duplicate records 3-4 times like
First Last
First Last
First
First Last
First Last
First Last
First
Empid Fname Lname Mgrid
1 x Last x
2 First x 1
Want to join and the result should be like "First Last" in one row
Tried with the query like,
"Select Distinct A.Fname, B.Lname
From Emp A join Emp B
on A.Mgrid = B.Empid"
or
"Select Distinct A.Fname, B.Lname
From Emp A, Emp B
where A.Mgrid = B.Empid"
or
"Select Distinct A.Fname, B.Lname
From Emp A
Left join Emp B on A.Mgrid = B.Empid"
but getting the results like,
First Last
First
Can any one help in removing the second row from the results?
by
Gunnas
BY
Siddu
i solved you are query like as follows
select d.fname+' '+d1.lname from dummy as d join dummy as d1 on d.mgrid=d1.empid
Results like this as,
"FirstLast"
thank you vary much....
Good artical for understand meaning of self join ...
thanx once again...
can u explain me plz...with an example...
e1 and e2 are the objects for the EMP table, we can use same table for the self join na, so we should declare like and use them.
Thanks,
JJ
* Using Stored Procedures
* sql queries
* groupby functions etc
* Joins
Complete explanation
Link here for Sql Tutorial
http://geeksprogrammings.blogspot.in/search/label/StructuredQueryLanguage%28SQL%29
Link here for joins explanation
geeksprogrammings.blogspot.in/2013/06/joins-in-sql.html