Solved

Self join confusing

Posted on 2011-09-11
4
350 Views
Last Modified: 2012-05-12
Can some one explain self with good example in detail with sample data,  mainly how the query  executed ?please explain step by step.
0
Comment
Question by:N_Sri
4 Comments
 
LVL 92

Assisted Solution

by:Patrick Matthews
Patrick Matthews earned 150 total points
ID: 36518748
A self-join is simply joining a table to itself.

For example, you might have a list of departments, with each department having a "parent":

tblDepts
-----------------------------
DeptID (PK)
DeptName
ParentDeptID

To run a query that lists all departments with their parents, if applicable--the department at the top of the hierarchy will not have a parent--use a self-join:

SELECT d1.DeptID, d1.DeptName, d1.ParentDeptID, d2.DeptName AS ParentDeptName
FROM tblDepts d1 LEFT JOIN
    tblDepts d2 ON d1.ParentDeptID = d2.DeptID

Open in new window

0
 
LVL 42

Accepted Solution

by:
dqmq earned 350 total points
ID: 36519114
Use self join when you need two (or more) rows of the same table combined into a single row in order to produce the result set.  Of course, for it to make logical sense, a row must have columns that support a relationship with other rows in the same table.

The classical example is when you have a hierarchical relationship.  You can retrieve the parent row along with the child row using a self join.  MathewsPatrick has illustrated that form quite nicely.  Note the LEFT JOIN in his example.  Self Join is not to be confused with LEFT JOIN! But, it is a necessary complement, in this case, in order to return departments that are at the top of the hierarchy (ParentDeptID is null or unmatched).  Suppose, instead, you want a query that returns all departments that report to Accounting.  Then, an INNER JOIN works quite fine because you don't care about the unmatched rows:

SELECT c.DeptID, c.DeptName
 FROM tblDepts c
 INNER JOIN tblDepts p ON c.ParentDeptID = p.DeptID
WHERE p.DeptName = 'Accounting'


A more complex use of self join is often applied to chronological sequences.  For example, a time-clock history with check-in and check-out records.  To compute the hours worked, you need to pair a check-out time with the check-in time preceding it.

Select out.empID, out.timeofday-in.timeofday as timeworked
  from timeclock in
 inner join timeclock out
  on in.empID = out.empID
and out.timeofday =
    (select min(m.timeofday) from timeclock m
       where m.empID = in.empID
           and m.timeofday > in.timeofday)  
               
 








 
0
 
LVL 7

Expert Comment

by:tampnic
ID: 36522060
Not an answer to your original question but as an extension to previous comments ...

Like dqmq and matthewspatrick say, self joins are usually used to accomplish heirarchical queries. SQL Server provides an ANSI compliant mechanism for heirarchical queries to be accomplished using the WITH clause and Common Table Expressions if more control/complexity is needed than the simple self join.

Here are two articles on the use of recursive sub-queries to accomplish a heirarchical query:
http://www.eggheadcafe.com/articles/sql_server_recursion_with_clause.asp
http://msdn.microsoft.com/en-us/library/ms186243.aspx

This is a little more advanced than a straightforward self join but the explanations in the articles may help shed some light on the problem you are addressing.

HTH,
  Chris
0
 

Author Closing Comment

by:N_Sri
ID: 36533189
thankyou
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question