954,593 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

SQL Problem: Retrieving information On Same Table via Aliases

Hi,

I am having trouble with retrieving records on my database.
My layout was this..

UsersList
  Username
  Firstname
  LastName
  Role

Records
  TheUser
  ApprovedBy
  DateApproved


The first text are the table names while the indented once are the field names.
I have a table named Records. TheUser and ApprovedBy was referring to the Username under the UsersList table.

Now my problem was, when I retrieve the records by aliases. I need to use the first name and last name of the users to generate report.

Example:

UsersList
	mzip
	Michael
	Zip
	Supervisor

	xtian
	Christian
	Holmes
	Trainee

Records
	xtian
	mzip
	1/22/2012 4:53:00 PM

If I will use this query, it will just show similar record.

SELECT (LastName + ', ' + FirstName) AS theTrainee, (LastName + ', ' + FirstName) AS PersonInCharge FROM UsersList
INNER JOIN Records ON UsersList.Username = Records.theUser
theTrainee      PersonInCharge 
Zip, Michael    Zip, Michael


What I need is

theTrainee      PersonInCharge 
Zip, Michael    Holmes, Christian


Any Ideas?
Michael

michaelzip
Newbie Poster
19 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

This should do the trick:

select a.LastName + ', ' + a.Firstname as theTrainee, b.LastName + ', ' + b.Firstname as PersonInCharge 
from Records r inner join UsersList a on r.TheUser = a.Username 
inner join UsersList b on r.ApprovedBy = b.Username


I haven't tested it, so it might contain typos.

adam_k
Practically a Posting Shark
804 posts since Jun 2011
Reputation Points: 256
Solved Threads: 149
 

It works! You're a genius mate!

michaelzip
Newbie Poster
19 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: