Solved

Self join confusing

Posted on 2011-09-11
4
343 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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now