Thursday, March 8, 2012

Copying data from multiple tables to one table

Hi,

I have 3 tables with the follwing schema

Table <Category>

{

UniqueID,

LastDate DateTime

}

Assume the follwing tables with data following the above schema

Table Cat1

{

1, D1

2, D2

3, D3

}

Table Cat2

{

2, D4

3,D5

4, D6

}

Table Cat3

{

1, D7

3,D8

5,D9

}

I have a Master and the schema is as follows

Table master

{

UniqueId,

Cat1 DateTime, -- This is same as the Table name

Cat2 DateTime, -- This is same as the Table name

Cat3 DateTime -- This is same as the Table name

}

After inserting the data from all these 3 tables, I want the my master table to look like this

Table Master

{

UniqueId cat1 cat2 Cat3

- --

1 D1 NULL D7

2 D2 D4 NULL

3 D3 D5 D8

4 NULL D6 NULL

5 NULL NULL D9

}

Please remember the column names will be same as that of table names

can any one pelase let me know the query t o acheive this

Thanks for your quick response

~Mohan Babu

Follow these steps

(a) Insert first table to master ie Cat1 to Master

Insert into TableMaster (UniqueID,Cat1) Select Col1,Col2 from Cat1

(b) Insert into master table from Cat2 only those uniqueid which are not in master

Insert into TableMaster (UniqueID,Cat2) Select Col1,Col2 from Cat2 Where Col1 not In (Select UniqueID from TableMaster )

(c) Update Cat2 column of master table

Update TableMaster Set Cat2=A.Col2 from Cat2 A

inner join TableMaster B on b.UniqueID=a.Col1

(d) Insert into master from Cat3

Insert into TableMaster (UniqueID,Cat3) Select Col1,Col2 from Cat3 Where Col1 not In (Select UniqueID from TableMaster )

(e) Update TableMaster Set Cat3=A.Col2 from Cat3 A

inner join TableMaster B on b.UniqueID=a.Col1

Madhu

No comments:

Post a Comment