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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Cross Apply or Join

Author  Topic 

russella
Starting Member

3 Posts

Posted - 2008-01-03 : 22:11:18
Hi All,

How can i query/join the to two tables?see below is my scenario with table1,table2 and results.

Table1

userid firstname lastname
james.thomas james thomas
john.johnson john johnson

Table2
userid name value
james.thomas country australia
john.johnson title singapore

Results:

userid | firstname | lastname| country| title
james.thomas | james | thomas | australia | manager
john.johnson | john | johnson | singapore | programmer

Any help is very much appreciated!

Thanks a lot!


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-01-03 : 22:51:17
Try this:-
SELECT t1.userid,t1.firstname,t1.lastname,c.value as 'country',t.value as 'title'
FROM Table1 t1
CROSS APPLY(SELECT value
FROM Table2
where userid=t1.userid
AND name='country') c
CROSS APPLY(SELECT value
FROM Table2
where userid=t1.userid
AND name='title') c
Go to Top of Page

russella
Starting Member

3 Posts

Posted - 2008-01-04 : 00:57:59
Hi Visakh16,

Thank you so much for your quick help!

More power!
Go to Top of Page

jezemine
Master Smack Fu Yak Hacker

2886 Posts

Posted - 2008-01-04 : 01:37:04
this seems simpler to me:


select t1.userid, t1.firstname, t1.lastname, t2.value as country, t3.value as title
from Table1 t1
left join Table2 t2 on t1.userid=t2.userid and t2.name='country'
left join Table2 t3 on t1.userid=t3.userid and t3.name='title'



elsasoft.org
Go to Top of Page

russella
Starting Member

3 Posts

Posted - 2008-01-04 : 01:49:56
is it possible to make the [Name] dynamic ('country,title')? for example a user wants to display only what he/she selected like country only? is it possible pass a parameters (Selected Items)?
Go to Top of Page

jezemine
Master Smack Fu Yak Hacker

2886 Posts

Posted - 2008-01-04 : 02:14:14
quote:
Originally posted by russella

is it possible to make the [Name] dynamic ('country,title')? for example a user wants to display only what he/she selected like country only? is it possible pass a parameters (Selected Items)?



sure, just pass them in params:


select t1.userid, t1.firstname, t1.lastname, t2.value as country, t3.value as title
from Table1 t1
left join Table2 t2 on t1.userid=t2.userid and t2.name=@name1
left join Table2 t3 on t1.userid=t3.userid and t3.name=@name2



elsasoft.org
Go to Top of Page
   

- Advertisement -