Business Logic with JOIN – Multiple Join examples in SQL-Server 2005:

Business Logic with JOIN – Multiple Join examples in SQL-Server 2005:
I wrote my previous article about different type of JOIN in SQL-Server 2005. Due to the space constraint in that article, complex example has not been given there, only few simple examples. I felt to explode this topic further by giving solution to some really needed business logic.
If you want to create report for blood testing laboratory, who used to check samples of employee of different companies for different purposes. Following should be the table structure, we will be creating three table. One will store information about Order received from different companies. Another one will be the detail of that order, means which company sent how much samples of how much employee?? And the last one is further more details about how much test should be performs on which sample???
Let us create three tables.
–CREATING FIRST ORDER TABLE
USE [AdventureWorks]
GO
/****** Object: Table [dbo].[Orders] Script Date: 03/08/2009 12:24:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Orders](
[OrderID] [varchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[OrderDate] [datetime] NOT NULL,
[CompanyName] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
PRIMARY KEY CLUSTERED
(
[OrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
Now, child table of above.
USE [AdventureWorks]
GO
/****** Object: Table [dbo].[OrderDetails] Script Date: 03/08/2009 12:37:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[OrderDetails](
[OrderID] [varchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[SampleNumber] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[SampleOfEmployee] [varchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[SampleReceivedDate] [datetime] NULL,
PRIMARY KEY CLUSTERED
(
[SampleNumber] ASC
)
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [dbo].[OrderDetails] WITH CHECK ADD CONSTRAINT [fk_orderid] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[OrderDetails] CHECK CONSTRAINT [fk_orderid]
One more child table.
USE [AdventureWorks]
GO
/****** Object: Table [dbo].[sampledetails] Script Date: 03/08/2009 12:43:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[sampledetails](
[SampleNumber] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[TestType] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
PRIMARY KEY CLUSTERED
(
[SampleNumber] ASC,
[TestType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
Now, this is time to insert few records on above tables.
–Received three order from two company
INSERT INTO Orders
SELECT ‘L1000’,‘2009-03-01’,‘Test Inc.’ UNION ALL
SELECT ‘L1001’,‘2009-03-02’,‘Zeel Inc.’ UNION ALL
SELECT ‘L1002’,‘2009-03-04’,‘ABC Inc.’
–received two sample for first order, one sample for second order
–sample for third order yet to receive
INSERT INTO OrderDetails
SELECT ‘L1000’,‘L1000-01’,‘James’,‘2009-03-01’ UNION ALL
SELECT ‘L1000’,‘L1000-02’,‘John’,‘2009-04-01’ UNION ALL
SELECT ‘L1001’,‘L1001-01’,‘Smita’,‘2009-03-05’
–details of sample, which test suppose to be performed
–on which sample
INSERT INTO SampleDetails
SELECT ‘L1000-01’,‘Cancer’ UNION ALL
SELECT ‘L1000-01’,‘AIDS’ UNION ALL
SELECT ‘L1000-02’,‘BP’ UNION ALL
SELECT ‘L1001-01’,‘AIDS’ UNION ALL
SELECT ‘L1001-01’,‘Cancer’
Well, now we are ready to pull data out of three tables with different type of JOIN which we have seen in my previous article.
NOTE: many different logic can be used to perform following tasks, I am giving this just to explain the use of JOIN otherwise there are some more facility which can handle all of the below situation other than join.
If you want to get OrderID, OrderDate, Company (who gave the order??), SampleNumber, EmployeeName (for which employee company has sent the sample??), TestType (which test to be performed in above tables?)
You can use following query which has used one LEFT OUTER JOIN and one INNER JOIN.
SELECT O.OrderID,O.OrderDate,O.CompanyName,
OD.SampleofEmployee,OD.SampleNumber,SD.TestType
FROM
ORDERS AS O
LEFT OUTER JOIN
ORDERDETAILS AS OD
ON
O.OrderID=OD.OrderID
INNER JOIN
SampleDetails AS SD
ON
OD.SampleNumber=SD.SampleNumber
If there is a need to find how many samples came from which company. Use following query with aggregate function COUNT.
SELECT
O.CompanyName,Count(SampleNumber) as ‘TOTAL’
FROM
ORDERS AS O
LEFT OUTER JOIN
ORDERDETAILS AS OD
ON
O.OrderID=OD.OrderID
GROUP BY O.CompanyName
ORDER BY TOTAL DESC
Reference: Ritesh Shah
Advertisements

Complete ref of SQL-Server Join, Inner Join, Left Outer Join, Right Outer Join, Full Outer Join, in SQL-Server 2005:

Complete ref of SQL-Server Join, Inner Join, Left Outer Join, Right Outer Join, Full Outer Join, in SQL-Server 2005:
Merging data is heart of SQL and it shows the depth of relational algebra as well as the power and flexibility of SQL. SQL is excellent at selecting the data and SQL Developer can be master by understanding the relational algebra.
Join seems known technology but it is fun all time. Developer can make very creative query with joins by making data twist and shout. Pulling the data out of join could be the answer of very big code of programming language with iteration. It is much faster than any loop in your code. I promise you will have fun by learning this powerful technique.
SQL-Server 2005 is relational database so you always need to join more than one table in order to get complete information out of data tables. Since, tables are self explanatory itself, order of table doesn’t matter.
Here are the types of available joins in SQL-Server 2005:
Note: AdventureWorks database is going to be used throughout in this chapter.
Inner Join: It’s a very common and frequently needed join. Common intersection will be pulled out in this kind of join. It means, it will compare the result sets of first table with result sets of second table based on common fields or based on primary key and foreign key relationship. Below given is an example of Inner Join.
SELECT Sales.SalesPerson.SalesPersonID,
Sales.SalesPersonQuotaHistory.SalesQuota
FROM Sales.SalesPerson
INNER JOIN
Sales.SalesPersonQuotaHistory
ON
Sales.SalesPerson.SalesPersonID=Sales.SalesPersonQuotaHistory.SalesPersonID
You can get join two table with SalesPersonID in above case as both have common field.
(Part of Outer Join) Left Outer Join: Include all rows from the left side table no matter whether matching rows are exists in right side table or not. It means that Outer join is an extended version of Inner Join as it not only gives your common intersection but it do gives non matching data from left side or right side along with intersection.
SELECT HumanResources.Employee.EmployeeID,HumanResources.Employee.NationalIDNumber,
HumanResources.EmployeeAddress.AddressID
FROM HumanResources.Employee Left Outer Join HumanResources.EmployeeAddress
ON
HumanResources.Employee.EmployeeID=HumanResources.EmployeeAddress.EmployeeID
Employee table is joined with EmployeeAddress table based on EmployeeID. Left out join has been used so it will list all employees, no matter where it meets associated entry in EmployeeAddress.
(Part of Outer Join) Right Outer Join: Include all rows from the right side table no matter whether matching rows are exists in left side table or not. It means that Outer join is an extended version of Inner Join as it not only gives your common intersection but it do gives non matching data from left side or right side along with intersection.
SELECT HumanResources.Employee.EmployeeID,HumanResources.Employee.NationalIDNumber,
HumanResources.EmployeeAddress.AddressID
FROM HumanResources.Employee Right Outer Join HumanResources.EmployeeAddress
ON
HumanResources.Employee.EmployeeID=HumanResources.EmployeeAddress.EmployeeID
Employee table is joined with EmployeeAddress table based on EmployeeID. Right outer join has been used so it will list all employees’ Address, no matter where it meets associated entry in EmployeeAddress.
(Part of Outer Join) Full Outer Join: Includes all rows from both tables regardless of match exists. It means it a union distinct of Left Outer Join and Right Outer Join.
SELECT HumanResources.Employee.EmployeeID,HumanResources.Employee.NationalIDNumber,
HumanResources.EmployeeAddress.AddressID
FROM HumanResources.Employee Full Outer Join HumanResources.EmployeeAddress
ON
HumanResources.Employee.EmployeeID=HumanResources.EmployeeAddress.EmployeeID
Self Join: A self-join refers back to itself. You can use this type of unary relationship for recursive purpose. Like employee table to find boss.
–creating table for self join
create table emp
(
ID int Identity(1,1),
Name Varchar(15),
BossID int
)
GO
–Inserting some records in above table.
Insert Into emp
SELECT ‘DM’,0 UNION ALL
SELECT ‘MA’,1 UNION ALL
SELECT ‘UC’,2 UNION ALL
SELECT ‘LU’,2
GO
–equi join which will find boss name for every employee, DM is a main boss in this case.
SELECT e.ID,e.Name,ep.Name as ‘boss name’
FROM emp e JOIN emp ep
on
e.bossid=ep.id
GO
There are few more types of join like theta join, equi join, natural join etc. which I will explain in coming article.
Reference: Ritesh Shah