query from two different tables

May 15th, 2009 - 05:35 am ET by Eric | Report spam
Hi,

I need to generate a table which is build from two other tables.
These tables have only one field in common.

table1: nr,name1,name2
table2: nr,place1,place2

I would like a query to give me the following:

table3: nr,name1,name2,place1,place2

example: 1,aaaa,bbbb,[blank],[blank]
2,[blank],[blank],ccccc,ddddd

the [blank] should be empty or null.

is this possible and how do I do this?

rg,
Eric
email Follow the discussionReplies 4 repliesReplies Make a reply

Replies

#1 Eric
May 15th, 2009 - 04:05 pm ET | Report spam
Thank your for the example.

I think I'm asking for something wrong here.

I'm going to use a different approach now.

I think it is better I do two select commands and then combine it within my
vb code somehow.

thanks again, I learned something about sql here.

rg,
Eric


"Russell Fields" wrote:

I don't understand why you would want this particular implementation, but I
believe that you are asking for:

CREATE TABLE table3
(nr INT,
name1 nvarchar(30) NULL,
name2 nvarchar(30) NULL,
place1 nvarchar(30) NULL,
place2 nvarchar(30) NULL)

INSERT INTO table3 (nr, name1, name2)
SELECT nr, name1, name2 FROM table1
INSERT INTO table3 (nr, place1, place2)
SELECT nr, place1, place2 FROM table1

Is nr unique per table? If so, you would only have 1 row of a particular nr
in each table. If that was the case, you could also create a table with the
results.
1,aaaa,bbbb,ccccc,ddddd

Assuming that there are non-matching rows, you could do:

INSERT INTO table3
SELECT COALESCE(table1.nr, table2.nr),
table1.name1, table1.name2,
table2.place1, table2.place2
FROM table1
FULL OUTER JOIN table2
ON table1.nr = table2.nr

Of course, when there are no matching rows you would get results like:
2,aaaa,bbbb,NULL,NULL
3,NULL,NULL,cccc,dddd

FWIW,
RLF

"Eric" wrote in message
news:
>I made an error. The output should look like:
>
> example: 1,aaaa,bbbb,[blank],[blank]
> 1,[blank],[blank],ccccc,ddddd
>
> rg,
> Eric
>
> "Eric" wrote:
>
>> Hi,
>>
>> I need to generate a table which is build from two other tables.
>> These tables have only one field in common.
>>
>> table1: nr,name1,name2
>> table2: nr,place1,place2
>>
>> I would like a query to give me the following:
>>
>> table3: nr,name1,name2,place1,place2
>>
>> example: 1,aaaa,bbbb,[blank],[blank]
>> 2,[blank],[blank],ccccc,ddddd
>>
>> the [blank] should be empty or null.
>>
>> is this possible and how do I do this?
>>
>> rg,
>> Eric
>>
>>
>>




Similar topics