简体   繁体   中英

SQL Join to only one record in one to many relationship

I have the following query:

SELECT c.[ClientID]
        ,u.[AccessId]
 FROM [tblClient] c
 INNER JOIN [tblUser] u ON u.[Id] = c.[UserId]

This tblUser has multiple ID's for each UserID row.

So it would look like this:

UserID    AccessID
1           AD2F0A-965B78414-2B34906F2-0127AA5A
1           ID2F0A9-65B784-142B34906-F20127AA5A
1           UD2F0A9-65B78-4142B34906F-20127AA5A
2           TD2F0A9-65B784142-B34906F-20127AA5A
2           RD2F0A9-65B784142B3-4906-F20127AA5A
3           WD2F0A96-5B784142-B34906F201-27AA5A 
3           ZD2F0A96-5B784-142B34-906F2-0127AA5A
3           CD2F0A965-B784142B3-4906F20-127AA5A

Is there a way to only get the top(or 1) AccessId for each UserID? It doesnt matter which AccessID i get, I just want 1 of them.

Thanks

SELECT c.[ClientID], MAX(u.[AccessId]) 
    FROM [tblClient] c 
        INNER JOIN [tblUser] u 
            ON u.[Id] = c.[UserId]
    GROUP BY c.[ClientID]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM