Reputation: 203
I have 3 tables in my database which is
table 1 (users)
userid(PK)
EmployeeName
table 2 (SubDept)
SubDeptID(PK)
Department
table 3 (SubDeptTransfer)
TransferID(PK)
userid(FK)
SubDeptID(FK)
here is my example table for Table 3
what i wanted to do is to be able to print the SubDeptID of user 100. The problem is since there are two userid of 100 its printing both. the mission is to be able to print only one data with a latter TransferID. What could be the best select statement for the problem?
Upvotes: 0
Views: 59
Reputation: 1038
I would do it like so:
SELECT subDeptId FROM SubDeptTransfer WHERE userId = 100 ORDER BY transferId DESC LIMIT 1
Upvotes: 2
Reputation: 1270091
The best way to do this is using the window function row_number()
:
select transferId, userId, subDeptId
from (select t.*,
row_number() over (partition by userid order by TransferId desc) as seqnum
from t
) t
where seqnum = 1
Upvotes: 2