473,750 Members | 2,265 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inner join to lookup values twice?

Folks,

My secnario involves two tables - ObservationRegi ster, and Person.
ObservationRegi ster contains most of the "useful" fields, including
the UserID of the person that raised the record, and the UserID of the
person to whom the record was assigned for action. I need to write a
query to return all values in the ObservationRegi ster record, but
instead of returning the UserIDs, I need to look up the actual name,
by looking up the name and userID in the Person table... doing that
once (for just one of the UserID fields) is easy - a quick inner join
does the job - but I effectively need to join to the Person table
"twice", for different keys....

Help? Please!? :)

Steve
Jul 20 '05 #1
4 8438
You join to the table twice, using different "table aliases" or "correlatio n
names" Here's a fairly simple example that I believe represents what you
want:

create table person
(UserID varchar(16) not null,
UserName varchar(24) not null,
constraint PK_Person primary key clustered (UserID))

create table ObservationRegi ster
(ORID int not null,
RaisingUser varchar(16) not null,
AssignedUser varchar(16),
ObservationDate datetime,
ObservationComm ent varchar(64),
constraint PK_ObservationR egister primary key clustered (ORID))
go

insert person (UserID,UserNam e) values ('User1','Raise r1')
insert person (UserID,UserNam e) values ('User2','Raise r2')
insert person (UserID,UserNam e) values ('User3','Raise r3')
insert person (UserID,UserNam e) values ('User4','Worke r4')
insert person (UserID,UserNam e) values ('User5','Worke r5')
insert person (UserID,UserNam e) values ('User6','Worke r6')

insert observationregi ster (orid, raisinguser, assigneduser,
observationdate ) values (1, 'user1', null,'21-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdate ) values (2, 'user2', null,'22-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdate ) values (3, 'user3', null,'23-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdate ) values (4, 'user1', 'user4','24-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdate ) values (5, 'user2', 'user5','25-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdate ) values (6, 'user3', 'user6','26-dec-2003')

select oreg.orid,
pr.username as raiser,
pa.username as assigned
from
observationregi ster oreg
inner join person pr /* 'pr' for person raising */
on oreg.raisinguse r = pr.userid
left outer join person pa /* 'pa' for person assigned */
on oreg.assignedus er = pa.userid

orid raiser assigned
----------- ------------------------ ------------------------
1 Raiser1 NULL
2 Raiser2 NULL
3 Raiser3 NULL
4 Raiser1 Worker4
5 Raiser2 Worker5
6 Raiser3 Worker6

"Steve Hall" <st*******@hotm ail.com> wrote in message
news:4c******** *************** ***@posting.goo gle.com...
Folks,

My secnario involves two tables - ObservationRegi ster, and Person.
ObservationRegi ster contains most of the "useful" fields, including
the UserID of the person that raised the record, and the UserID of the
person to whom the record was assigned for action. I need to write a
query to return all values in the ObservationRegi ster record, but
instead of returning the UserIDs, I need to look up the actual name,
by looking up the name and userID in the Person table... doing that
once (for just one of the UserID fields) is easy - a quick inner join
does the job - but I effectively need to join to the Person table
"twice", for different keys....

Help? Please!? :)

Steve

Jul 20 '05 #2
[posted and mailed, please reply in news]

Steve Hall (st*******@hotm ail.com) writes:
My secnario involves two tables - ObservationRegi ster, and Person.
ObservationRegi ster contains most of the "useful" fields, including
the UserID of the person that raised the record, and the UserID of the
person to whom the record was assigned for action. I need to write a
query to return all values in the ObservationRegi ster record, but
instead of returning the UserIDs, I need to look up the actual name,
by looking up the name and userID in the Person table... doing that
once (for just one of the UserID fields) is easy - a quick inner join
does the job - but I effectively need to join to the Person table
"twice", for different keys....


Something like this:

SELECT FirstUser = p1.name, SecondUser = p2.name
FROM ObservationRegi ster or
JOIN Person p1 ON or.FirstUserID = p1.UserId
JOIN Person p2 ON or.SecondUserId = p2.UserID
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #3
You can avoid joining twice with this trick:

select
oreg.orid,
max(case when person.userid = oreg.raisinguse r then person.username
end) as raiser,
max(case when person.userid = oreg.assignedus er then person.username
end) as assigned
from
observationregi ster oreg
inner join person
on oreg.raisinguse r = person.userid
or oreg.assignedus er = person.userid
group by oreg.orid

-- Steve Kass
-- Drew University
-- Ref: 08B3FAD8-9929-43B7-AAD5-30E4EBC53ED9

DHatheway wrote:
You join to the table twice, using different "table aliases" or "correlatio n
names" Here's a fairly simple example that I believe represents what you
want:

create table person
(UserID varchar(16) not null,
UserName varchar(24) not null,
constraint PK_Person primary key clustered (UserID))

create table ObservationRegi ster
(ORID int not null,
RaisingUser varchar(16) not null,
AssignedUser varchar(16),
ObservationDate datetime,
ObservationComm ent varchar(64),
constraint PK_ObservationR egister primary key clustered (ORID))
go

insert person (UserID,UserNam e) values ('User1','Raise r1')
insert person (UserID,UserNam e) values ('User2','Raise r2')
insert person (UserID,UserNam e) values ('User3','Raise r3')
insert person (UserID,UserNam e) values ('User4','Worke r4')
insert person (UserID,UserNam e) values ('User5','Worke r5')
insert person (UserID,UserNam e) values ('User6','Worke r6')

insert observationregi ster (orid, raisinguser, assigneduser,
observationdat e) values (1, 'user1', null,'21-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdat e) values (2, 'user2', null,'22-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdat e) values (3, 'user3', null,'23-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdat e) values (4, 'user1', 'user4','24-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdat e) values (5, 'user2', 'user5','25-dec-2003')
insert observationregi ster (orid, raisinguser, assigneduser,
observationdat e) values (6, 'user3', 'user6','26-dec-2003')

select oreg.orid,
pr.username as raiser,
pa.username as assigned
from
observationregi ster oreg
inner join person pr /* 'pr' for person raising */
on oreg.raisinguse r = pr.userid
left outer join person pa /* 'pa' for person assigned */
on oreg.assignedus er = pa.userid

orid raiser assigned
----------- ------------------------ ------------------------
1 Raiser1 NULL
2 Raiser2 NULL
3 Raiser3 NULL
4 Raiser1 Worker4
5 Raiser2 Worker5
6 Raiser3 Worker6

"Steve Hall" <st*******@hotm ail.com> wrote in message
news:4c******* *************** ****@posting.go ogle.com...

Folks,

My secnario involves two tables - ObservationRegi ster, and Person.
ObservationRe gister contains most of the "useful" fields, including
the UserID of the person that raised the record, and the UserID of the
person to whom the record was assigned for action. I need to write a
query to return all values in the ObservationRegi ster record, but
instead of returning the UserIDs, I need to look up the actual name,
by looking up the name and userID in the Person table... doing that
once (for just one of the UserID fields) is easy - a quick inner join
does the job - but I effectively need to join to the Person table
"twice", for different keys....

Help? Please!? :)

Steve



Jul 20 '05 #4
Erland,

Spot on! Huge Thanks - I'd been trying to solve it all afternoon!

Cheers!

Steve

Erland Sommarskog <so****@algonet .se> wrote in message news:<Xn******* *************@1 27.0.0.1>...
[posted and mailed, please reply in news]

Steve Hall (st*******@hotm ail.com) writes:
My secnario involves two tables - ObservationRegi ster, and Person.
ObservationRegi ster contains most of the "useful" fields, including
the UserID of the person that raised the record, and the UserID of the
person to whom the record was assigned for action. I need to write a
query to return all values in the ObservationRegi ster record, but
instead of returning the UserIDs, I need to look up the actual name,
by looking up the name and userID in the Person table... doing that
once (for just one of the UserID fields) is easy - a quick inner join
does the job - but I effectively need to join to the Person table
"twice", for different keys....


Something like this:

SELECT FirstUser = p1.name, SecondUser = p2.name
FROM ObservationRegi ster or
JOIN Person p1 ON or.FirstUserID = p1.UserId
JOIN Person p2 ON or.SecondUserId = p2.UserID

Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6416
by: Prem | last post by:
Hi, I am having many problems with inner join. my first problem is : 1) I want to know the precedance while evaluating query with multiple joins. eg. select Employees.FirstName, Employees.LastName, TerritoryID, Employees.EmployeeID, RegionID, ProductID from Employees
4
8105
by: DCM Fan | last post by:
{CREATE TABLEs and INSERTs follow...} Gents, I have a main table that is in ONE-MANY with many other tables. For example, if the main table is named A, there are these realtionships: A-->B A-->C A-->D
8
6325
by: kieran | last post by:
Hi, I have the following sql statement. I originally had the statement with two INNER JOINS but in some situations was getting an error so changed the last INNER JOIN to a LEFT OUTER JOIN (as is seem below). This seemed to work but i am unsure why and would like to know in case it falls over again. Why did the two INNER JOINS not work, and am I correct to use the LEFT OUTER JOIN in this context. As you can see the table 'tblStaff1_2'...
3
44532
by: mheydman | last post by:
I apologize if this has been asked before- I searched google but could not find a concrete answer. I recently inherited a database whose t-sql code is written in a format that I find difficult to read (versus the format I have used for years). I have tested the queries below using the SQL Profiler, and both have identical costs. Is there any advantage of one format over the other?
5
4045
by: jason.evans | last post by:
Hi there. I am having an intrigueing problem. I have a query which left joins another query to itself twice. The original query is derived from a linked table in SQLServer 2000. When I run it on my pc It runs fine. However for other users in the office, it behaves as an inner join. ie it only returns the records fo which the join fields equal each other. This happens on every other pc
6
9315
by: dmonroe | last post by:
hi group -- Im having a nested inner join problem with an Access SQl statement/Query design. Im running the query from ASP and not usng the access interface at all. Here's the tables: tblEmployees empId -- EmpName -- EmpRole -- EmpManager -------....------------.... ---------....--------------- 1........ dan yella..........1..........2
52
6341
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible variations(combination of fields), - then act on each group in some way ...eg ProcessRs (oRs as RecordSet)... the following query will get me the distinct groups
0
2350
by: katupilar | last post by:
I am writing a tool to interface with a couple of tables in SQL Server 2000. I usually write my queries with an Inner Join to bring in fields from seperate tables and load that to a DataSet. I'm wondering if this way is more efficient then using a DataSet.Relations.Add approach or a combination of the two. When should you use an Inner Join over a Relation within a dataset and vice versa? For example is this possible: ...
0
1284
by: stanlew | last post by:
Happy New Year everyone! I'm new to both T-SQL and this forum. I'm currently doing an internship and my first task was to create a small program which will send an email detailing the sales of the previous day versus monthly targets and sales. Most of the parts were figured out and eveything was done in Visual Studio. The gist of the code was written in one large chunk of SQL code, as below: SELECT derivedtbl_1.family AS 'Family',...
0
8838
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9339
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6804
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4713
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2804
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.