Parent table (tblLog) has three fields
UserID
Time
Action
Child Table (tblRole) has three fields
UserID
Role
TransDate
I want the query to give me the three fields from tblLog and the Role information from tblRole for each UserID. The problem is that UserID in tblRole is not unique because the table contains historical roles. So what I need to do it only include the UserID and Role for the Max of the TransDate. My understanding is that this is straight forward but I don't know how to do it. Here is the sql that I am trying to fix:
SELECT L.[ID]
,L.[UserID]
,L.[Time]
,L.[Action]
,R.Role
FROM [TEST111].[dbo].[tblLog] as L
Join [TEST111].[dbo].[tblRole] as R
On L.[UserID] = R.[UserID]
Here is sample data from tblRole*:
ID UserID Role TransDate
1 U001 Super 1/1/2015
2 U001 Super 2/15/2015
3 U001 Mgr 3/7/2015
4 U002 Line 2/10/2015
5 U002 Super 5/4/2015
6 U004 Mgr 4/4/2015
7 U005 Super 1/15/2015
*I had previously said that this was sample date from tblLog
You can do this with a
ROW_NUMBER
over theTransDate
for eachUserId
:This query will pull the most recent transaction information for each
UserId
.You need to
GROUP BY
the fields that you are determining the value for, then add theMAX
aggregate for the value you're analyzing.