SQL Server Join Example

By:   |   Updated: 2021-07-20   |   Comments (29)   |   Related: 1 | 2 | 3 | 4 | 5 | 6 | 7 | > JOIN Tables


Problem

I am new to Microsoft SQL Server and want to learn about the JOIN options for the relational database. What are all of the JOIN options in SQL Server? What is the significance of each of the options? I am a little confused on the differences and syntax, can you provide some examples and explanations? Are JOINs only for SELECT statements?  Check out this SQL Tutorial to learn about SQL Server INNER JOIN syntax.

Solution

Joining tables to obtain the needed data for a query, script or stored procedure is a key concept as you learn about SQL Server development. In a nutshell, joins are typically performed in the FROM clause of a table or view for the SELECT, INSERT...SELECT, SELECT...INTO, UPDATE and DELETE statements. In previous versions of SQL Server, join logic could also have been included in the WHERE clause with = (INNER JOIN), *= (LEFT OUTER JOIN), =* (RIGHT OUTER JOIN), etc. syntax, but the support has been reduced and the best practice in SQL Server is to use the syntax outlined in the examples below.

Before we jump into code, let's provide some baseline information on the types of JOINs in SQL Server:

  • SQL INNER JOIN - Match rows between the two tables specified in the INNER JOIN statement based on one or more columns having matching data - Equi Join.  Preferably the join is based on referential integrity enforcing the relationship between the tables to ensure data integrity.
    • Just to add a little commentary to the basic definitions above, in general the INNER JOIN option is considered to be the most common join needed in applications and/or queries.  Although that is the case in some environments, it is really dependent on the database design, referential integrity and data needed for the application.  As such, please take the time to understand the data being requested then select the proper join option.
    • Although most join logic is based on matching values between the two columns specified, it is possible to also include logic using greater than, less than, not equals, etc.
  • SQL LEFT OUTER JOIN - Based on the two tables specified in the join clause, all data is returned from the left table.  On the right table, the matching data is returned in addition to NULL values where a record exists in the left table, but not in the right table.
    • Another item to keep in mind is that the LEFT and RIGHT OUTER JOIN logic is opposite of one another.  So you can change either the order of the tables in the specific join statement or change the JOIN from left to right or vice versa and get the same results.
  • SQL RIGHT OUTER JOIN - Based on the two tables specified in the join clause, all data is returned from the right table.  On the left table, the matching data is returned in addition to NULL values where a record exists in the right table but not in the left table.
  • SQL Self Join - In this circumstance, the same table is specified twice with two different aliases in order to match the data within the same table.
  • SQL CROSS JOIN - Based on the two tables specified in the join clause, a Cartesian product is created if a WHERE clause does filter the rows.  The size of the Cartesian product is based on multiplying the number of rows from the left table by the number of rows in the right table.  Please heed caution when using a CROSS JOIN.
  • SQL FULL JOIN - Based on the two tables specified in the join clause, all data is returned from both tables regardless of matching data.

Let's walk through examples from the AdventureWorks sample database that is available for SQL Server to provide example SQL statements for each type of JOIN then provide some insight into the usage and sample result sets.

SQL Server INNER JOIN Example

In the following query we have a SQL INNER JOIN clause between the Sales.SalesOrderDetail and Production.Product tables.  The tables are aliased with the following:  SOD for Sales.SalesOrderDetail and P for Production.Product.  The JOIN condition is based on matching rows in the SOD.ProductID and P.ProductID columns.  The records are filtered by only returning records with the SOD.UnitPrice (column name) greater than 1000.  Finally, the result set is returned in order with the most expensive first based on the ORDER BY clause and only the highest 100 products based on the TOP clause.

USE MSSQLTips; 
GO 
SELECT  TOP 100 P.ProductID, 
 P.Name, 
 P.ListPrice, 
 P.Size, 
 P.ModifiedDate, 
 SOD.UnitPrice, 
 SOD.UnitPriceDiscount,
 SOD.OrderQty,
 SOD.LineTotal 
FROM Sales.SalesOrderDetail SOD 
INNER JOIN Production.Product P 
 ON SOD.ProductID = P.ProductID 
WHERE SOD.UnitPrice > 1000 
ORDER BY SOD.UnitPrice DESC
GO

SQL Server LEFT OUTER JOIN Example

In the following query we are combining two concepts to show that more than two tables can be JOINed in one SELECT statement and more than one JOIN type can be used in a single SELECT statement.  In the sample code below, we are retrieving the matching rows between the Person.Contact and Sales.SalesPerson tables in conjunction with all of the data from the Sales.SalesPerson table and matching rows in the Sales.SalesTerritory table.  For records that exist Sales.SalesPerson table and not in the Sales.SalesTerritory table, NULL values are returned for the columns in the Sales.SalesTerritory.  In addition, this code uses two columns to order the data i.e. ST.TerritoryID and C.LastName.

USE MSSQLTips;
GO
SELECT  C.ContactID,
 C.FirstName,
 C.LastName,
 SP.SalesPersonID,
 SP.CommissionPct,
 SP.SalesYTD,
 SP.SalesLastYear,
 SP.Bonus,
 ST.TerritoryID,
 ST.Name,
 ST.[Group],
 ST.SalesYTD
FROM Person.Contact C
INNER JOIN Sales.SalesPerson SP
 ON C.ContactID = SP.SalesPersonID
LEFT OUTER JOIN Sales.SalesTerritory ST 
 ON ST.TerritoryID = SP.TerritoryID
ORDER BY ST.TerritoryID, C.LastName
GO

SQL Server RIGHT OUTER JOIN Example

In an effort to explain how the RIGHT OUTER JOIN and LEFT OUTER JOIN is logically a reciprocal on one another, the following query is re-written version of the LEFT OUTER JOIN above.  As you can see the JOIN order and tables are different, but the final result set matches the LEFT OUTER JOIN logic.   In the sample code below, we are retrieving the matching rows between the Person.Contact and Sales.SalesPerson tables in conjunction with all of the data from the Sales.SalesPerson table and matching rows in the Sales.SalesTerritory table.  For records that exist Sales.SalesPerson table and not in the Sales.SalesTerritory table, NULL values are returned for the columns in the Sales.SalesTerritory.

USE MSSQLTips;
GO 
SELECT  C.ContactID, 
 C.FirstName, 
 C.LastName, 
 SP.SalesPersonID,
 SP.CommissionPct,
 SP.SalesYTD,
 SP.SalesLastYear,
 SP.Bonus,
 ST.TerritoryID,
 ST.Name, ST.[Group],
 ST.SalesYTD 
FROM Sales.SalesTerritory ST 
RIGHT OUTER JOIN Sales.SalesPerson SP 
 ON ST.TerritoryID = SP.TerritoryID 
INNER JOIN Person.Contact C 
 ON C.ContactID = SP.SalesPersonID 
ORDER BY ST.TerritoryID, C.LastName
GO

SQL Server Self Join Example

In this example, we are actually self-joining to the HumanResources.Employee table.  We are doing this to obtain the information about the Employee and Manager relationship in the HumanResources.Employee table.  In conjunction with that JOIN logic we are also joining to the Person.Contact twice in order to capture the name and title data based on the original Employee and Manager relationships.  In addition, another new concept introduced in this query is aliasing each of the column names.  Although we could have done so in the previous examples, we made point of doing so in this query to differentiate between the Employee and Manager related data.

USE MSSQLTips;
GO
SELECT  M.ManagerID AS 'ManagerID',
 M1.ContactID AS 'ManagerContactID',
 M1.FirstName AS 'ManagerFirstName',
 M1.LastName AS 'ManagerLastName',
 M.Title AS 'ManagerTitle',
 E.EmployeeID AS 'EmployeeID',
 E1.ContactID AS 'EmployeeContactID',
 E1.FirstName AS 'EmployeeFirstName',
 E1.LastName AS 'EmployeeLastName',
 E.Title AS 'EmployeeTitle'
FROM HumanResources.Employee E 
INNER JOIN HumanResources.Employee M 
 ON E.ManagerID = M.EmployeeID 
INNER JOIN Person.Contact E1 
 ON E1.ContactID = E.ContactID 
INNER JOIN Person.Contact M1 
 ON M1.ContactID = M.ContactID
ORDER BY M1.LastName
GO

SQL Server CROSS JOIN Example

As indicated above, please heed caution when running or modifying this query in any SQL Server database environment.  The result set is intentionally limited by the TOP 100 clause and the WHERE clause to prevent a Cartesian product, which is the result of each of the rows from the left table multiplied by the number of rows in the right table.

USE MSSQLTips; 
GO 
SELECT  TOP 100 P.ProductID, 
 P.Name, 
 P.ListPrice, 
 P.Size, 
 P.ModifiedDate, 
 SOD.UnitPrice, 
 SOD.UnitPriceDiscount,
 SOD.OrderQty,
 SOD.LineTotal 
FROM Sales.SalesOrderDetail SOD 
CROSS JOIN Production.Product P 
WHERE SOD.UnitPrice > 3500 
ORDER BY SOD.UnitPrice DESC
GO

SQL Server FULL OUTER JOIN Example

In our last example, we have modified the logic from the LEFT OUTER JOIN example above and converted the LEFT OUTER JOIN syntax to a FULL OUTER JOIN.  In this circumstance, the result set is the same as the LEFT OUTER JOIN where we are returning all of the data between both tables and data not available in the Sales.SalesTerritory is returned as NULL.

USE MSSQLTips;
GO
SELECT  C.ContactID,
 C.FirstName,
 C.LastName,
 SP.SalesPersonID,
 SP.CommissionPct,
 SP.SalesYTD,
 SP.SalesLastYear,
 SP.Bonus,
 ST.TerritoryID,
 ST.Name,
 ST.[Group],
 ST.SalesYTD
FROM Person.Contact C
INNER JOIN Sales.SalesPerson SP
 ON C.ContactID = SP.SalesPersonID
FULL OUTER JOIN Sales.SalesTerritory ST 
 ON ST.TerritoryID = SP.TerritoryID
ORDER BY ST.TerritoryID, C.LastName
GO
Next Steps


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Jeremy Kadlec Jeremy Kadlec is a Co-Founder, Editor and Author at MSSQLTips.com with more than 300 contributions. He is also the CTO @ Edgewood Solutions and a six-time SQL Server MVP. Jeremy brings 20+ years of SQL Server DBA and Developer experience to the community after earning a bachelor's degree from SSU and master's from UMBC.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2021-07-20

Comments For This Article




Tuesday, February 16, 2021 - 1:43:55 PM - Jeremy Kadlec Back To Top (88247)
David,

Can you please provide a bit more insight into your question with some sample data and what the final output should be?

Thank you,
Jeremy Kadlec

Friday, February 12, 2021 - 4:35:10 PM - David Back To Top (88233)
How can I join overlapping data from two different tables? I have an Event: E1 @ T1 and Event: E2 @ T2. I'm trying to correlate the state model when T2 happens. When I use an outer join the data is there but it doesn't correlate correctly.

From the first table: E1 happens @ T1= 2/12/2021 0:44 with event = running
From the second table: E2 happens @ 2/12/2021 7:50 with event = OOS

Thursday, July 6, 2017 - 9:48:34 AM - krish Back To Top (58958)

examples should be understandable and simple and there should be table to understand 


Thursday, September 29, 2016 - 10:03:02 AM - Jeremy Kadlec Back To Top (43453)

Ankit,

I am not sure I understand your question completely.  I assume you are missing an ORDER BY clause.  Here is one example - https://www.mssqltips.com/sqlservertutorial/135/select-with-order-by/.

HTH.

Thank you,
Jeremy Kadlec
Community Co-Leader


Thursday, September 29, 2016 - 6:16:03 AM - ankit sharma Back To Top (43445)

hi sir,

The sequence of recordset is verying in each joins .

how to predict the exact sequence for each type of joins.

 

regards:

Ankit sharma 

 


Tuesday, January 13, 2015 - 1:50:03 AM - Srikanth Back To Top (35910)

Yes!  It helped me a lot in "Joins" concepts & can u elaborate with Tables with their Structure.. plzz


Tuesday, October 14, 2014 - 2:25:46 PM - Saurabh Back To Top (34955)
Plz add snapshots of tbles also, before joining and after joing 

Friday, August 16, 2013 - 2:32:37 PM - nz Back To Top (26353)

*** NOTE *** - If you want to include code from SQL Server Management Studio (SSMS) in your post, please copy the code from SSMS and paste the code into a text editor like NotePad before copyingI have usertable,grouptable and groupuser table.I have written example query to fetch usertable,group and groupusertable to show only one role for an user but need your help writing to fetch multiple roles for an user,

SAy for example USERID=1 FNAME=ANDY and LNAME=ROberts has(role) should be displayed by selecting mulple role in G.name =,TRAINING,IT etc,

On the query it should select one or more values from the column g.name to save for the userprofile.

I couldnt think of this from top of my head as im just trying to learn sql.

User table doesn't have any common column to fetch the result from group table instead we need to join usergroup table which has common column as code in usertable and usergrouptable and groupid in grouptable and usergroup table.

SELECT T.UID,
T.FNAME ,T.LNAME
,T.EMAIL_ADDRESS 
,T.ORIG AS HIERARCHY
,T.BUSINESS_NUMBER 
,T.APPROVERNAME
,T.MYOFFICE 
,G.NAME AS ROLE 
FROM [USER] AS T
INNER JOIN [GROUPUSER] AS UG ON T.CODE = UG.CODE

INNER JOIN [GROUP] AS G ON UG.GROUPID = G.GROUPID


your help is appreciated


Monday, July 22, 2013 - 8:30:01 AM - BalaKrishna.B Back To Top (25936)

GOOD Explanation..nice article


Thursday, July 18, 2013 - 7:37:58 AM - girijesh Back To Top (25893)
complaint number DESCRIPTION QTY Remarks
complaint number1 cp1 1 2
cp2 1 2
cp3 1 2
cp4 1 2
cp5 1 2
       
complaint number2 cp3 1 2
cp5 1 2

hi friends plz help me how to do it...?

 

tabel2 

 

A14135/206 eg 1                r1
A14135/206 eg1 1              r2
A14135/206 eg2             r3
A14135/206 eg3 1  r4

table 1

 

 

i have two table on table1 and table2..?

 

table1 one i have comlaint no single../

table2 complaint no two i have more complaints...

 

finally i wil display like above how to do it..?

 

Thanks & Regards

Girijesh kumar

8892257056

"If u help some one , some other one surely help u" ~Giri

 


Wednesday, January 23, 2013 - 4:19:39 AM - siva Back To Top (21638)

Im having a doubt can u please help me to solve over this problem ...

data having in my table


name     type      date

siva     1         27/10/2010
siva     2         29/10/2010
siva     3         30/10/2010
saro     3         28/10/2010
saro     1         29/10/2010


but i need result like this



name      old     new     date

siva      1        2     29/10/2010
siva      2        3     30/10//2010
saro      3        1     29/10/2010


Friday, November 16, 2012 - 5:10:38 AM - Jeremy Kadlec Back To Top (20373)

Dee,

I think this is what you need:

Select  w.*,
 m1.Cure,
  m2.MillThickness1,
 m2.rollnumber
From tblWinder w
LEFT OUTER JOIN tblMatLab1 m2
 ON w.RollNumber = m2.RollNumber
LEFT OUTER JOIN tblMatLab2 m1
 ON w.RollNumber = m1.RollNumber

Be sure to test it as compared to your original code.

HTH.

Thank you,
Jeremy Kadlec


Thursday, November 15, 2012 - 9:11:55 AM - Dee Back To Top (20356)

 

I'm new to SQL How would I code the following properly with LEFT OUTER JOIN

Select

w

.*,

m1

.Cure,

m2

.MillThickness1,

m2.rollnumber

From

tblWinder w

,

tblMatLab1 m2

,

tblMatLab2 m1

Where

w

.RollNumber *= m1.RollNumber AND

w

.RollNumber *= m2.RollNumber


Friday, October 5, 2012 - 10:38:56 AM - Jeremy Kadlec Back To Top (19801)

Pradeep,

Here are some tips on NOLOCK:

http://www.mssqltips.com/sqlservertip/2470/understanding-the-sql-server-nolock-hint/

http://www.mssqltips.com/sqlservertip/1232/remove-some-sql-server-blocking-issues-with-the-nolock-hint/

http://www.mssqltips.com/sqlservertip/1646/execute-sql-server-select-command-without-locking/

 

Here is a tip on CROSS JOINs:

http://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/

 

Beyond the information in this tip on SELF JOINs, I will see if we can author a tip on that topic.

HTH.

Thank you,
Jeremy Kadlec


Thursday, October 4, 2012 - 5:50:50 AM - pradeep kumar Back To Top (19786)

Can you give brief explanation about NOLOCK..., Cross join when to use it and self join.

thank you..,


Friday, June 22, 2012 - 4:56:23 PM - Jeremy Kadlec Back To Top (18177)

Huong,

Thank you for the feedback.  Please let me know if this explanation makes sense or not.

Are ProductID, Name, ListPrice, Size, ModifiedDate fields from Table Product table?

JTK - Yes.  The "P." in front of the column name is the table alias.  A table alias is used when joining tables in order to not have to type the full table name.  Aliasing is could be considered as an approach to save typing.

Are UnitPrice, UnitPriceDiscount, OrderQty, LineTotal fields from SalesOrderDetail table?

JTK - Yes.  This is aliasing again.

What is P?

JTK - P is the alias for the "Production.Product" table.

What is SOD?

JTK - SOD is the alias for the "Sales.SalesOrderDetail" table.

Why we need them?

JTK - Aliasing is a technique to save typing.  You can type out the entire table name for each column or ensure each column name is unique.  I would just alias the tables and columns to make the code easier to read.

What is Production?

JTK - It is a schema.  See below for the explanation.

What is Sales? is it a schema?

JTK - "Sales" is the schema.  At a high level, you can consider a schema as a security container.

BTW - On a related note, I tried to give detailed explanations for a beginner in this tutorial (http://www.mssqltips.com/sqlservertutorial/2515/sample-table-for-sql-server-insert-examples/) on a related topic.  Please let me know if that makes sense.  I want to make sure the community gets value from the tips.

Thank you,
Jeremy Kadlec


Thursday, June 21, 2012 - 10:15:48 AM - Huong Back To Top (18154)

Hello There,  I am just a beginner in SQL,

I am looking at this inner join code example and don’t understand what the followings are, Would you please help explain it to me?  Your help is greatly appreciated!  Thanks much,

Are ProductID, Name, ListPrice, Size, ModifiedDate fields from Table Product table?
Are UnitPrice, UnitPriceDiscount, OrderQty, LineTotal fields from SalesOrderDetail table?
What is P?
What is SOD?
Why we need them?
What is Production?
What is Sales? is it a schema?


USE MSSQLTips;

GO
SELECT  TOP 100 P.ProductID,
 P.Name,
 P.ListPrice,
 P.Size,
 P.ModifiedDate,
 SOD.UnitPrice,
 SOD.UnitPriceDiscount,
 SOD.OrderQty,
 SOD.LineTotal
FROM Sales.SalesOrderDetail SOD
INNER JOIN Production.Product P
 ON SOD.ProductID = P.ProductID
WHERE SOD.UnitPrice > 1000
ORDER BY SOD.UnitPrice DESC
GO


Wednesday, May 30, 2012 - 7:25:56 AM - Peter Back To Top (17721)

The Database am using is MSSQL server 2005. I have a Database on Access so I am trying to replicate that database from access to the MSSql 05 database engine. We are moving from Access to MSSqlserver and we have a retail inventory management application interface that works with the Access Database built using C# on visual studio IDE. so I have to come up with a database that fits the access database including columns,primary keys,foriegn keys and all. The database columns/P.K/F.K are outlined below:

 

SELECT CUSTOMER_REGISTRATION.ID, CUSTOMER_REGISTRATION.SURNAME, CUSTOMER_REGISTRATION.OTHER_NAME,CUSTOMER_REGISTRATION.PHONE#, CUSTOMER_REGISTRATION.ADDRESS, GRN.DATE, GRN.PRODUCT, GRN.MAKE, GRN.MODEL, GRN.SERIAL#, RECEIVABLE.STAFF_NAME, RECEIVABLE.PHONE# AS Expr1, RECEIVABLE.DATE AS Expr2, RECEIVABLE.SERIAL# AS Expr3, RECEIVABLE.CHEQUE, MAKE_REGISTRATION.MAKE_ID, MAKE_REGISTRATION.MAKE AS Expr4, MODEL_REGISTRATION.MODEL_ID, MODEL_REGISTRATION.MODEL AS Expr5, PRODUCT_REGISTRATION.PRODUCT_ID, PRODUCT_REGISTRATION.PRODUCT AS Expr6,STAFF_REGISTRATION.STAFF_ID, STAFF_REGISTRATION.STAFF_NAME AS Expr7, SELLING_PRICE.PRODUCT AS Expr8,SELLING_PRICE.MAKE AS Expr9, SELLING_PRICE.MODEL AS Expr10, SELLING_PRICE.PRICE

FROM MAKE_REGISTRATION INNER JOIN GRN ON MAKE_REGISTRATION.MAKE = GRN.MAKE INNER JOIN MODEL_REGISTRATION ON GRN.MODEL = MODEL_REGISTRATION.MODEL INNER JOIN PRODUCT_REGISTRATION ON GRN.PRODUCT = PRODUCT_REGISTRATION.PRODUCT INNER JOIN RECEIVABLE ON GRN.SERIAL# = RECEIVABLE.SERIAL# INNER JOIN SELLING_PRICE ON MAKE_REGISTRATION.MAKE = SELLING_PRICE.MAKE INNER JOIN STAFF_REGISTRATION ON RECEIVABLE.STAFF_NAME = STAFF_REGISTRATION.STAFF_NAME CROSS JOIN CUSTOMER_REGISTRATION                        

 

Now I want to connect the GRN table to Selling_price Table? using (GRN.PRODUCT = [SELLING PRICE TABLE].PRODUCT) AND (GRN.MAKE = [SELLING PRICE TABLE].MAKE) AND (GRN.MODEL = [SELLING PRICE TABLE].MODEL) on the MSSql 2005 database  How do i create a relationship between this two tables using the following sql statements on the access database?          SELECT [CUSTOMER REGISTRATION].SURNAME, [CUSTOMER REGISTRATION].[OTHER NAME], [CUSTOMER REGISTRATION].ADDRESS, RECEIVABLE.Date, RECEIVABLE.PHONE, RECEIVABLE.SERIAL, RECEIVABLE.CHECK, GRN.PRODUCT, GRN.MAKE, GRN.MODEL, [SELLING PRICE TABLE].PRICE, RECEIVABLE.STAFF

FROM (([CUSTOMER REGISTRATION] INNER JOIN RECEIVABLE ON [CUSTOMER REGISTRATION].[PHONE NO] = RECEIVABLE.PHONE) INNER JOIN GRN ON RECEIVABLE.SERIAL = GRN.SERIAL) INNER JOIN [SELLING PRICE TABLE] ON (GRN.PRODUCT = [SELLING PRICE TABLE].PRODUCT) AND (GRN.MAKE = [SELLING PRICE TABLE].MAKE) AND (GRN.MODEL = [SELLING PRICE TABLE].MODEL);

 

Tuesday, May 1, 2012 - 6:14:59 AM - manal Back To Top (17216)

Hello

about my last question I make tow viows and I make join between them after that

but now I want to ask you about how can I make trigger on insert statment

and work in this way ( if the rowId -in inserte statment -is founded make update in the samw row and if not insert new one)


Monday, April 30, 2012 - 2:54:45 PM - manal Back To Top (17212)

fisrt of all thank you very much but it does't work

the statement is correct but the way of grouping is wrrong

 


Monday, April 30, 2012 - 9:00:08 AM - Dom Back To Top (17201)

Manal:  Does this help?

Select c.Name, sum (p.Amount) as Total_Amt, sum (v.Value) as Total_Value

from Customer c

       join Payment p on c.??? = p.????

       join Invoice v on c.??? = v.???

group by c.Name


Monday, April 30, 2012 - 8:56:20 AM - Dom Back To Top (17200)

I think you should have pointed out that the ON clause can do more than just present the matching columns.  For example, you can use:

FROM Sales.SalesOrderDetail SOD
INNER JOIN Production.Product P
ON SOD.ProductID = P.ProductID and P.Name < 'M'

Also, it is crucial to keep in mind the logical processing sequence.  All joins, without exceptions, are logically cross joins, then the ON clause is executed to filter out the records that do not return true.

One more point.  The tables in the from clause are processed from left to right.


Saturday, April 28, 2012 - 4:55:02 PM - manal Back To Top (17179)

Thanke you very much


Saturday, April 28, 2012 - 4:52:51 PM - manal Back To Top (17178)

Hello

My name is Manal

I'm So interesting in SQL server but I found problem in Grouping for example I have three Tables(Customer,Payments,Invoice)

Customer related with Payment

and Customer related with Invoice but no relation between Payment and Invoice

and I want To make groupink to give me

(customername,sum(payment.Amount),sum(Invoice.Value) for every customer but actauly I try alot but there always some error in result not in statments


Monday, January 16, 2012 - 8:56:25 AM - Jeremy Kadlec Back To Top (15660)

torontom,

Thank you for the feedback.  From the initial publication of this tip to today, it looks like Microsoft has changed the AdventureWorks database and this query no longer parses.

In the short term, I will update the tip so that the code makes sense and plan to re-write this tip to include a data model to make sure the examples are clear.

Thank you,
Jeremy Kadlec


Friday, January 6, 2012 - 6:05:11 PM - torontom Back To Top (15538)

 

self join sample:

GO
SELECT  M.ManagerID AS 'ManagerID',
 M1.ContactID AS 'ManagerContactID',
 M1.FirstName AS 'ManagerFirstName',
 M1.LastName AS 'ManagerLastName',
 M.Title AS 'ManagerTitle',
 E.EmployeeID AS 'EmployeeID',
 E1.ContactID AS 'EmployeeContactID',
 E1.FirstName AS 'EmployeeFirstName',
 E1.LastName AS 'EmployeeLastName',
 E.Title AS 'EmployeeTitle'
FROM HumanResources.Employee E 
INNER JOIN HumanResources.Employee M 
 ON E.ManagerID = M.ManagerID 
INNER JOIN Person.Contact E1 
 ON E1.ContactID = E.ContactID 
INNER JOIN Person.Contact M1 
 ON M1.ContactID = M.ContactID
ORDER BY M1.LastName
 
should be: E.ManagerID =M.EmployeeId, isn't it?

Sunday, October 30, 2011 - 7:29:32 AM - JustJay Back To Top (14964)

+1


Saturday, October 29, 2011 - 4:30:09 PM - Raul Back To Top (14963)

Very good. 


Thursday, February 11, 2010 - 8:31:09 AM - syousuf Back To Top (4884)
Thanks a lot.It was helpful.














get free sql tips
agree to terms