Sunteți pe pagina 1din 13

Home

All Articles
SQL Interview Q & A
Resume
Statistics
Performance
Contact Me
Tool
Journey to SQLAuthority
Personal Notes of Pinal Dave
Feeds: Posts Comments
« SQL SERVER 2005 Microsoft SQL Server Management Pack for Microsoft Operations Ma
nager 2005 Download SQL Server MOM 2005
SQL SERVER Database Coding Standards and Guidelines Introduction »
SQL SERVER 2005 Explanation and Example SELF JOIN
June 3, 2007 by pinaldave
A self-join is simply a normal SQL join that joins one table to itself. This is
accomplished by using table name aliases to give each instance of the table a se
parate name. Joining a table to itself can be useful when you want to compare va
lues in a column to other values in the same column. A join in which records fro
m a table are combined with other records from the same table when there are mat
ching values in the joined fields. A self-join can be an inner join or an outer
join. A table is joined to itself based upon a field or combination of fields th
at have duplicate data in different records. The data-type of the inter-related
columns must be of the same type or needs to cast them in same type.
When all of the data you require is contained within a single table, but data ne
eded to extract is related to each other in the table itself. Examples of this t
ype of data relate to Employee information, where the table may have both an Emp
loyee s ID number for each record and also a field that displays the ID number of
an Employee s supervisor or manager. To retrieve the data tables are required to r
elate/join to itself.
Another example which can be tried on SQL SERVER 2005 sample database AdventureW
orks is to find products that are supplied by more than one vendor. Please refer
the sample database for table structure.
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID = pv2.VendorID
ORDER BY pv1.ProductID
Reference : Pinal Dave (http://blog.SQLAuthority.com) , BOL Example courtesy
Share this:
Facebook
Digg
StumbleUpon
Reddit
Print
Email
Ads by Google
Posted in Pinal Dave, SQL, SQL Authority, SQL Joins, SQL Query, SQL Scripts, SQL
Server, SQL Tips and Tricks, T SQL, Technology | 40 Comments
Like
Be the first to like this post.
40 Responses
on June 21, 2007 at 5:24 am | Reply
Vivek
Gud Arcticle.
on July 4, 2007 at 7:22 am | Reply
manoj
liked it. Its a good article
on July 5, 2007 at 4:20 am | Reply
Sonali kedar
Nice Article
on November 22, 2007 at 5:27 pm | Reply
harsh
really gud
on November 22, 2007 at 5:29 pm | Reply
shweta
I really liked this article.
on November 22, 2010 at 3:40 pm | Reply
naresh
really i like ur response
on December 15, 2010 at 11:52 pm | Reply
siddu
me 2.. :)
on December 7, 2007 at 10:07 am | Reply
somasekhar
very nice article
on February 6, 2008 at 2:26 pm | Reply
vijay
didnt understand please give an easier example i am just learning SQL please for
ward me 1 if possible all help will be appriciated
on March 18, 2008 at 2:31 pm | Reply
Nikesh Sinha
i want to know detail info about cursor and trigger can u help me .
on March 22, 2008 at 5:17 pm | Reply
Trang
With your example, I have the following problem:
List pairs of vendor names who have the same ProductID. But if I use Self Join l
ike the below script, the result will be redundant (2 pairs are the same except
their orders). What should I do to get the exact pairs I need? Thank you.
USE AdventureWorks;
GO
SELECT DISTINCT pv1.VendorName, pv2.VendorName
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID != pv2.VendorID
(The result will be:
Vendor1 Vendor2
Vendor2 Vendor1
Vendor3 Vendor4
Vendor4 Vendor3

)
on June 4, 2008 at 5:20 pm | Reply
Aditya Soni
Keep it Up
on July 18, 2008 at 4:38 pm | Reply
Giribabu
nice article on self join
on July 24, 2008 at 8:08 pm | Reply
Logesh
Nice Example
on August 29, 2008 at 11:54 am | Reply
Sumit
Nice Example
on September 13, 2008 at 3:19 pm | Reply
Rajesh
very nice article for self join
on October 3, 2008 at 10:39 pm | Reply
Chander Sharma
Gud article for selef join..
on October 14, 2008 at 1:07 am | Reply
Ivana
I think that the example needs to be corrected in the AND part of the code. Prod
uctID needs to be the same, but the VendorID must be different to get products s
upplied by multiple vendors!
AND pv1.VendorID pv2.VendorID
on February 26, 2009 at 5:25 pm | Reply
SQL SERVER - 2008 - Interview Questions and Answers - Part 2 Journey to SQL Auth
ority with Pinal Dave
[...] This is a particular case when one table joins to itself, with one or two
aliases to avoid confusion. A self join can be of any type, as long as the joine
d tables are the same. A self join is rather unique in that it involves a relati
onship with only one table. The common example is when company has a hierarchal
reporting structure whereby one member of staff reports to another. Self Join ca
n be Outer Join or Inner Join. (Read More Here) [...]
on March 18, 2009 at 12:30 am | Reply
lakshmi
I think above example needs to be modified to get the correct result,
i have used cte(common table expression) for that:
with vendorcount(productidcount) as
(
select productid from purchasing.productvendor
group by productid having count(vendorid)>1
)
select productidcount,vendorid from vendorcount inner join Purchasing.ProductVe
ndor
on productidcount=productid
any suggestions would be appreciated
on April 11, 2009 at 1:54 am | Reply
Jaswinder
You are one man with great words.
on May 5, 2009 at 8:21 pm | Reply
Faruk Ahmed
Excellent!!!
on May 14, 2009 at 9:05 pm | Reply
Kiran
I think the query should be modified as below:
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID pv2.VendorID
ORDER BY pv1.ProductID
on July 16, 2010 at 12:42 pm | Reply
danish khan
it works efficiently
on May 14, 2009 at 9:05 pm | Reply
Kiran
AND pv1.VendorID pv2.VendorID
on May 14, 2009 at 9:07 pm | Reply
Kiran
Administrator :
I am not able to place not equal to
between pv1.VendorID And pv2.VendorID
on May 15, 2009 at 7:58 am | Reply
Imran Mohammed
@Kiran
Post your query and post what error you see ?
IM.
on May 28, 2009 at 3:03 pm | Reply
Clive Paterson
Using less than in the join will eliminate the duplicate results:
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID < pv2.ProductID
AND pv1.VendorID < pv2.VendorID
ORDER BY pv1.ProductID1
Image the results set as a square grid where every row from pv1 is join with eve
ry row from pv2. Now, using a less than in the join will only join row from pv2
which have an ID greater than the ID in pv1, eliminating duplicates:
pv2
0 0 0 0 0 0
x 0 0 0 0 0
p x x 0 0 0 0
v x x x 0 0 0
1 x x x x 0 0
x x x x x 0
on June 24, 2009 at 10:27 am | Reply
Sanda
I have one observation regarding the example you gave:
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID = pv2.VendorID
ORDER BY pv1.ProductID
You said it will find products that are supplied by more than one vendor . This que
ry returns all products from the table, not just the ones supplied by 2 or more
vendors
Maybe you meant something more like this ( instead of =)
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID pv2.VendorID
ORDER BY pv1.ProductID
or even
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID pv2.VendorID
ORDER BY pv1.ProductID
on December 4, 2009 at 12:21 pm | Reply
Chandraakant H P
Nice and important article about self join,really its informative.
on December 16, 2009 at 11:27 am | Reply
Pravin
When we select multiple columns with Distinct as Clause
it does not gives distinct values Please see below Eg.
Employee is the Table with values
Santosh Patil 19000
Shilpa Shinde 18000
Ajit 20000
Pramod 15000
Pravin 21000
Prakash 15000
Ajit 35000
Query is
select distinct ename,salary from employee
O/P show is
Ajit 20000
Ajit 35000
Prakash 15000
Pramod 15000
Pravin 21000
Santosh Patil 19000
Shilpa Shinde 18000
Here there is Duplication of Name Ajit.
Plz Help me in sorting out this Problem.
Awaiting for Your Favourable reply.
Regards.
on December 16, 2009 at 8:47 pm | Reply
Brian Tkatch
@Pravin
DISTINCT works on the entire record, not just one COLUMN.
Something likw: select ename, MAX(salary) from employee GROUP BY ename; might wo
rk for you.
on January 23, 2010 at 9:57 am | Reply
hassum
I d like to make a qury to give me back the confliction beween starttime and endti
me and the period between them,
i want to insert a new field to Lecture table so that it must be not conflicted
with the time of other lecture for the same teacher .
thank for help.
on January 29, 2010 at 5:02 pm | Reply
Aseem
you are man of vision
on May 19, 2010 at 12:27 pm | Reply
Srinu
hi Pinal Dave,
i have a doubt in self join,
i have written query like this.
SELECT DISTINCT R.NDC,R1.NDC,
R.NPT_PRICEX as LastPrice,
R1.NPT_PRICEX as NewPrice,
from RNP2_NDC_PRICE R
join
RNP2_NDC_PRICE R1
on R1.NDC=R.NDC
and R1.IsActive= TRUE
and R.IsActive= FALSE
iam getting duplicate records through this query,because
the table having more than one non active records with same NDC.
please help me to avoid duplicate records.
on May 19, 2010 at 12:29 pm | Reply
Srinu
Result iam getting like this.
00002323560 00002323560 189.00000 213.88000
00002323560 00002323560 200.34000 213.88000
00002323701 00002323701 374.39999 399.70001
00002323704 00002323704 3533.33008 3997.00000
00002323704 00002323704 3744.00000 3997.00000
00002323730 00002323730 106.00000 119.91000
00002323730 00002323730 112.32000 119.91000
00002323733 00002323733 353.32999 399.70001
00002323733 00002323733 374.39999 399.70001
00002323734 00002323734 112.32000 119.91000
on May 20, 2010 at 11:58 pm | Reply
Paul
some of you (Srinu, Pravin) are not reading all the comments. Clive Paterson has
the solution about eliminating the duplicate records in his comment. So simple.
as Clive said:
Using less than in the join will eliminate the duplicate results:
meaning join on the record1.ID < record2.ID as part of your join.
clive's comment:
http://blog.sqlauthority.com/2007/06/03/sql-server-2005-explanation-and-example-
self-join/#comment-52507
on July 8, 2010 at 7:02 am | Reply
SQL SERVER The Self Join Inner Join and Outer Join Journey to SQL Authority with
Pinal Dave
[...] be the outer join, I often get a request for an example for the same. I ha
ve created example using AdventureWorks Database of Self Join earlier, but that
was meant for inner join as well. Let us create a new example today, where we [.
..]
on August 12, 2010 at 10:43 am | Reply
ASHOK
dear sir
your articles are really very use full for all users .
thanks a lot for create it.
on December 21, 2010 at 8:03 am | Reply
Anas Teinah
i think u dont need self join to answer the query
find products that are supplied by more than one vendor
here is my solution
SELECT ProductID, count(VendorID) as Num OF Vendors
FROM Purchasing.ProductVendor pv1
GROUP BY ProductID
HAVING count(VendorID) > 1
ORDER BY ProductID
thank u in advance

Comments RSS
Leave a Reply
Your email address will not be published. Required fields are marked *
Name *
Email *
Website

Notify me of follow-up comments via email.


Send me site updates

Community Tools

About Pinal Dave


Pinal Dave is a Microsoft Technology Evangelist (Database and BI). He has writte
n over 1700 articles on the subject on his blog at http://blog.sqlauthority.com.
He has 7+ years of hands-on experience. He holds a Masters of Science degree an
d a number of certifications, including MCTS, MCDBA and MCAD (.NET). He is also
Regional Mentor for PASS Asia. Prior to joining Microsoft he was awarded Microso
ft MVP award for three continuous years for his contribution in community.

About Nupur Dave


Nupur Dave love technology simply because it makes life more convenient. She is
devoted to technology because it touches our heart makes our daily lives easier.
Among the many technological programs she uses and embraces Windows Live most b
ecause she can do lots of things with ease from photo management to movies; busi
ness emails to personal social media connections.
Blog Stats
26,182,895 (25 Million+)
Email Subscription
Enter your email address to subscribe to this blog and receive notifications of
new posts by email.

Disclaimer
This is a personal weblog. The opinions expressed here represent my own and not
those of my employer. For accuracy and official reference refer to MSDN/ TechNet
/ BOL. My employer do not endorse any tools, applications, books, or concepts me
ntioned on the blog. I have documented my personal experience on this blog.
SQLAuthority Links
Subscribe to Newsletter
My Homepage
Windows Live Blog
--------------------
Top Downloads
PDF Downloads
Script Downloads
Script Bank
Favorite Scripts
All Scripts - 1
All Scripts - 2
All Scripts - 3
Top Articles
Best Articles
Favorite Articles - 1
Favorite Articles - 2
--------------------
SQL Interview Q & A
SQL Coding Standards
SQL FAQ Download
--------------------
Jobs @ SQLAuthority

Home
All Articles
SQL Interview Q & A
Resume
Statistics
Performance
Contact Me
Community Rules
Copyright
Tool
Idera
Red Gate
Expressor
Embarcadero
Categories
About Me (116)
Best Practices (128)
Business Intelligence (33)
Data Warehousing (47)
Database (302)
DBA (135)
DMV (9)
MVP (145)
PASS (14)
Readers Contribution (69)
Readers Question (78)
SharePoint (7)
Software Development (69)
SQL Add-On (99)
SQL Backup and Restore (73)
SQL BOL (11)
SQL Coding Standards (21)
SQL Constraint and Keys (57)
SQL Cursor (28)
SQL Data Storage (59)
SQL DateTime (46)
SQL DMV (18)
SQL Documentation (276)
SQL Download (284)
SQL Error Messages (152)
SQL Function (132)
SQL Humor (29)
SQL Index (146)
SQL Interview Questions and Answers (64)
SQL Joins (76)
SQL Milestone (20)
SQL Optimization (143)
SQL PASS (11)
SQL Performance (319)
SQL Puzzle (40)
SQL Security (126)
SQL Server DBCC (42)
SQL Server Management Studio (39)
SQL Service Pack (13)
SQL Stored Procedure (112)
SQL String (26)
SQL System Table (61)
SQL Trigger (24)
SQL User Group (57)
SQL Utility (142)
SQL View (26)
SQL Wait Stats (32)
SQL Wait Types (33)
SQL White Papers (61)
SQL XML (12)
SQLAuthority (578)
SQL Training (16)
SQLAuthority Author Visit (131)
SQLAuthority Book Review (25)
SQLAuthority News (533)
SQLAuthority Website Review (42)
SQLServer (162)
Tech (1347)
Pinal Dave (1336)
SQL Scripts (759)
Technology (1725)
PostADay (146)
SQL (1725)
SQL Authority (1725)
SQL Query (1725)
SQL Server (1725)
SQL Tips and Tricks (1725)
T SQL (1725)
Top Posts & Pages
SQL SERVER - Insert Data From One Table to Another Table - INSERT INTO SELECT -
SELECT INTO TABLE
SQL SERVER - Retrieve Current Date Time in SQL Server CURRENT_TIMESTAMP, GETDATE
(), {fn NOW()}
SQL SERVER - Insert Multiple Records Using One Insert Statement - Use of UNION A
LL
SQL SERVER - FIX : ERROR : (provider: Named Pipes Provider, error: 40 - Could no
t open a connection to SQL Server) (Microsoft SQL Server, Error: )
SQL SERVER - Convert Text to Numbers (Integer) - CAST and CONVERT
SQL SERVER - Import CSV File Into SQL Server Using Bulk Insert - Load Comma Deli
mited File Into SQL Server
SQL Server Interview Questions and Answers Complete List Download
SQL SERVER - Shrinking Truncate Log File - Log Full
SQL SERVER - 2005 List All Tables of Database
SQL SERVER - 2008 - Interview Questions and Answers Complete List Download
SQL SERVER - 2008 - Step By Step Installation Guide With Images
SQL SERVER - How to Rename a Column Name or Table Name
Top 5 Commenters
1989 - Madhivanan
460 - Imran Mohammed
287 - Brian Tkatch
266 - Ramdas Jaya
161 - Marko Parkkola
Authors
pinaldave
SQL SERVER FIX ERROR Service Logon Failure (ObjectExplorer)
SQLAuthority News Facebook Page and Twitter Connect Using Social Media
SQL SERVER SQL Server Compression Estimator Codeplex
SQL SERVER Attending MVP Open Day May 2011
SQLAuthority News Restart Remote Computer Shutdown Remote Computer
SQL SERVER Vote for My Session in SQL PASS
SQL SERVER Import CSV File into Database Table Using SSIS
SQL SERVER expressor 3.2 Release Review
SQL SERVER Resource Database ID 32767
SQL SERVER Common Table Expression (CTE) and Few Observation
Archives
May 2011
April 2011
March 2011
February 2011
January 2011
December 2010
November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
May 2010
April 2010
March 2010
February 2010
January 2010
December 2009
November 2009
October 2009
September 2009
August 2009
July 2009
June 2009
May 2009
April 2009
March 2009
February 2009
January 2009
December 2008
November 2008
October 2008
September 2008
August 2008
July 2008
June 2008
May 2008
April 2008
March 2008
February 2008
January 2008
December 2007
November 2007
October 2007
September 2007
August 2007
July 2007
June 2007
May 2007
April 2007
March 2007
February 2007
January 2007
December 2006
November 2006
Twitter
#sql #SQLServer SQL SERVER FIX ERROR Service Logon Failure (ObjectExplorer) http
://bit.ly/kCTsyW #SQLAuthority 3 hours ago
.@TechNetIndia SQL SERVER FIX ERROR Service Logon Failure (ObjectExplorer) http:
//bit.ly/lBLt2Y @MSDNIndia 3 hours ago
SQL SERVER - FIX - ERROR - Service Logon Failure (ObjectExplorer) http://wp.me/p
2NUQ-3mD 3 hours ago
The #SQLAuthority Daily is out! http://bit.ly/hboCYg 11 hours ago
2800 total follower - the number is good :) 15 hours ago
Blog at WordPress.com.
Theme: MistyLook by Sadish.

S-ar putea să vă placă și