Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Self join confusing

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

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
In this article I will describe the Backup & Restore 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.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to shrink a transaction log file down to a reasonable size.

839 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