August 12, 2013 at 12:55 pm
Hi All;
. I am testing some code with temporary tables. I have let’s say table 1 which I will call “mother table”. Here what it looks like.
ID Letter Data1
1 A 23
2 B 24
3 C 25
4 D 12
5 E 14
6 F 10
7 G 12
I am trying to join data from two tables which I will call “child1” and “child2” to the mother table on matches from letter column to have something like this.
ID Letter Data1 LetterC DataC
1 A 23 A 123
2 B 24 B 124
3 C 25 C 125
4 D 12 D 127
5 E 14 E 128
6 F 10 F 129
7 G 12 G 130
Here is “Child1” and “Child2” respectively
ID Letter DataC2
1 D 127
2 E 128
3 F 129
4 G 130
ID Letter DataC1
1 A 123
2 B 124
3 C 125
I have tried for one hour to come up with some code, but it seems that I am only able to get only data from one table joined to the mother table with the following query. I’m stuck and was wondering if any suggestion or code for a poor soul like me. Here is what I have so far. thanks
USE TEMPDB
IF exists (SELECT * FROM Mother AS M inner join dbo.cHILD1 AS C1 ON M.Letter = C1.LETTER)
begin
SELECT M.LETTER, C1.LETTER, M.DATA1, C1.DATAC1 FROM Mother as M
inner join child1 as c1 on c1.letter = m.Letter
end
else
begin
select M.Letter , C2.Letter, M.data1, C2.DataC2 from Mother as m
inner join child2 as c2 on c2.letter = m.Letter
end
August 12, 2013 at 1:16 pm
Try this code and see if it works for you:
select m.id, m.letter, m.data1, coalesce(c1.letter, c2.letter), coalesce(c1.data1, c2.data1)
from @Mother m
left join @child1 c1 on c1.letter = m.Letter
left join @child2 c2 on c2.letter = m.Letter
NOTE: You may have to change some of the table names to match your tables.
Also, for future posts, it would be nice if you could post your DDL and Insert statements like this:
declare @Mother table
(
ID int,
Letter char(1),
data1 int
)
insert @Mother (id, letter, data1) values
(1, 'A', 23)
,(2, 'B', 24)
,(3, 'C', 25)
,(4, 'D', 12)
,(5, 'E', 14)
,(6, 'F', 10)
,(7, 'G', 12)
declare @child1 table
(
ID int,
Letter char(1),
data1 int
)
insert @child1 (ID, Letter, data1) values
(1, 'A', 123)
,(2, 'B', 124)
,(3, 'C', 125)
declare @child2 table
(
ID int,
Letter char(1),
data1 int
)
insert @child2 (ID, Letter, data1) values
(1, 'D', 127)
,(2, 'E', 128)
,(3, 'F', 129)
,(4, 'G', 130)
It makes it so much easier and faster to come up with a possible solution.
__________________________________________________________________________________________________________
How to Post to get the most: http://www.sqlservercentral.com/articles/Best+Practices/61537/
August 12, 2013 at 1:28 pm
Hi;
That did it! thanks for the speedy response and for the heads up for the post format.
Cheers,
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply