[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Self join confusing

Posted on 2011-09-11
4
Medium Priority
?
386 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
[X]
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
4 Comments
 
LVL 93

Assisted Solution

by:Patrick Matthews
Patrick Matthews earned 450 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 1050 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
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.

649 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