It’s hard to get a good title for this question, but i will explain it thoroughly below. I’ll be simplifying these tables a bit to make the question a bit easier to ask.
I have a table called ‘User’ with the following columns:
UserRowId (PK)
FirstName
LastName
RegionRowId (FK)
Active
I have a table called ‘Region’ with the following columns:
RegionRowId
RegionDesc
UserRowId
The logic here is, a user belongs to a ‘Region’ which is noted by the RegionRowId in the User table. Each region (in the ‘Region’ table) has a regional manager which is noted by the ‘UserRowId’ column in the ‘Region’ table (a FK from the ‘User’ table).
I have a table called ‘UserTime’ with the following columns:
UserTimeRowId (PK)
UserRowId (FK)
Hours
Sales
The logic here is a user (mapped by UserRowId) reports hours and sales which get stored in this table. Each time a user reports sales/hours, a new row is created.
What I’m trying to accomplish:
I’m trying to write a query that will pull the FirstName, LastName, the regional manager for this user, the sum of the hours, and the sum of the sales.
Here’s what i have so far:
Query:
SELECT dbo.[User].FirstName, dbo.[User].LastName,
dbo.[Region].UserRowId AS RegManager, dbo.[Region].RegionDesc AS Desc,
SUM(dbo.[UserTime].Sales) AS Sales, SUM(dbo.[UserTime].Hours) AS Hours
FROM dbo.[UserTime]
INNER JOIN dbo.[User] ON dbo.[UserTime].UserRowid = dbo.[User].UserRowId
INNER JOIN dbo.[Region] ON dbo.[User].RegionRowId = dbo.[Region].RegionRowId
WHERE dbo.[User].Active = 1
GROUP BY dbo.[User].FirstName, dbo.[User].LastName,
dbo.[Region].UserRowId, dbo.[Region].RegionDesc
Output (example):
FirstName LastName RegManager RegionDesc Sales Hours
Bob Man 773 NYC 500 5
What i am having trouble with is:
I cannot (for the life of me) get the LastName of the regional manager (RegManager column in the output above) instead of the UserRowId. I know in my query i am pulling dbo.[Region].UserRowId so obviously that’s what i’ll get in the output. However, what i need is to use that ID to cross-reference the User table to pull the name of that manager.
When i try to join the user table and the region table by the UserRowId, i get a list of regional managers instead of a list of users, and a column of the regional managers for that user.
Do i need a subquery in there to accomplish this?
Any help is appreciated and please let me know if I need to clarify anything to get to a solution.
Thank you
You don’t need subqueries, but you need to use aliases, so that you can JOIN the same table (the user table in this case) multiple times without creating an ambiguity.