Solved

Self join confusing

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Copy data to New Year 9 32
SQL 2014 missing dll from Bin? 3 32
the way to learn Microsoft BI 13 46
T-SQL: Need Group By to use "fuzzy logic"?? 3 18
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 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.
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.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

749 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