Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
davidais
Starting Member
17 Posts |
Posted - 2012-10-04 : 09:21:00
|
Hi all,I need to link orderNo to projectNo on two tablesBetween the two tables, this depends on the combination of both [name] and [state]How would I link the two tables as linking either [name] or [state] results in duplicates? Table example:table1orderNo name state________________________________________order1 bob stateX order2 bob stateyorder3 jim stateXorder4 jim stateY table2name state projectNo________________________________________bob stateX project1bob statey project2jim stateX project3jim stateY project4 SELECT orderNo, projectNo FROM table1 LEFT JOIN table2 on table1.name=table1.name Many thanks,D |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2012-10-04 : 09:36:00
|
| Please provide expected output--Chandu |
 |
|
|
davidais
Starting Member
17 Posts |
Posted - 2012-10-04 : 09:43:33
|
This is what I want:orderNo projectNoorder1 project1order2 project2order3 project3order4 project4 Currently this is what i get:orderNo projectNoorder1 project2order1 project1order2 project2order2 project1order3 project4order3 project3order4 project4order4 project3 |
 |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2012-10-04 : 09:50:52
|
| DECLARE @table1 TABLE (orderNo varchar(20), name varchar(6), state varchar(10))INSERT INTO @table1 SELECT 'order1', 'bob', 'stateX' UNION ALLSELECT 'order2', 'bob', 'statey' UNION ALLSELECT 'order3', 'jim', 'stateX' UNION ALLSELECT 'order4', 'jim', 'stateY' DECLARE @table2 TABLE (name varchar(20), state varchar(6), projectno varchar(10))INSERT INTO @table2 SELECT 'bob', 'stateX', 'project1' UNION ALLSELECT 'bob', 'statey', 'project2' UNION ALLSELECT 'jim', 'stateX', 'project3' UNION ALLSELECT 'jim', 'stateY', 'project4' SELECT OrderNo, ProjectNoFROM @table1 t1 JOIN @table2 t2ON t1.name = t2.name AND t1.state = t2.state --Chandu |
 |
|
|
davidais
Starting Member
17 Posts |
Posted - 2012-10-04 : 09:54:31
|
Thanks but what would I do if I had two tables with thousands of records in each?I come from a Access background and the migration is proving difficult, in Access I would have joined the both [name] and [state] with the resulting code.LEFT JOIN table2 on table1.name=table1.name AND LEFT JOIN table2 on table1.state=table1.state SQL doesn't seem to like the AND operator used with JOINS... |
 |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2012-10-04 : 10:02:35
|
| TryFROM table1 JOIN table2 ON table1.name = table2.name AND table1.state = table2.state--Chandu |
 |
|
|
davidais
Starting Member
17 Posts |
Posted - 2012-10-04 : 10:27:25
|
| Ahhhhh, whoops - cheers for that! |
 |
|
|
|
|
|
|
|