Usually, in a normalized database the values related to a particular column will be referenced in other table.
Considering, there is company with 1000 engineers. In storing the employees, instead of storing engineer as the designation for each employee. Normal forms advised
us to store the engineer value in a small table with id as reference. This id can be stored in the employee table.
So that, it will improve the storage.
Now, I got all the data segregated into different tables and I need to join it into a single result set.
In that case,we will opt join operations in SQL Server. It will enable you to consolidate the data and provide you in an expected format. There are various joins available in SQL Server.
Let's see inner join option in SQL Server. This will join the table mutually based on a common column. The syntax looks like,
table1 inner join table2 on table1.column=table2.column
Let's see some example to learn the join operation in sql server.
-- lets see a chatting messenger example,
-- Am creating three tables, 1 holds the name of the person and 2 holds the mapping between the friends.
--Considering am giving a friends request to another user
drop table venkatTable
create table venkatTable(id int identity(1,1) primary key, nam varchar(100))
insert into venkatTable values('Venkatesan Prabu')
insert into venkatTable values('Subashini')
insert into venkatTable values('Jayakantham')
insert into venkatTable values('Arunachalam')
insert into venkatTable values('Santhi')
drop table friendTable
create table friendTable(id int, friendid int, valueStatus int)
insert into friendTable values(1,2,0)
insert into friendTable values(1,3,1)
insert into friendTable values(2,4,0)
insert into friendTable values(2,3,2)
drop table status
create table status(id int, status varchar(100))
insert into status values(1,'Approved')
insert into status values(0,'pending')
insert into status values(2,'DisApproved')
Now, Lets join tableA, TableB and TableC directly :
select a.nam,b.id,b.friendid,c.status
from venkatTable a inner join friendTable b on a.id=b.id
inner join status c on b.valueStatus = c.id
Joining tableA and TableB on another combination:
select a.nam,b.id,b.friendid
from venkatTable a inner join friendTable b on b.friendid=a.id
Fetching the name, friendname and Status (By joining three tables) :
select distinct t.nam,t1.nam,t.status,t.id,t.friendid,t1.id ,t1.friendid from
(
select row_number() over(order by b.id,b.friendid) as r1, a.nam,b.id,b.friendid,c.status
from venkatTable a inner join friendTable b on a.id=b.id
inner join status c on b.valueStatus = c.id
)t
inner join (
select row_number() over(order by b.id,b.friendid) as r2,a.nam,b.id,b.friendid
from venkatTable a inner join friendTable b on b.friendid=a.id
)
t1 on t.r1=t1.r2
Here we have used row_number() function of SQL Server 2005. It's used to generate the row numbers in your result set.
Thanks and Regards,
No comments:
Post a Comment