SQL只能在一对多关系中加入一条记录

时间:2011-05-13 16:48:09

标签: sql

我有以下查询:

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

此tblUser为每个UserID行都有多个ID。

所以它看起来像这样:

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

有没有办法只为每个UserID获取top(或1)AccessId?我得到哪个AccessID无关紧要,我只想要其中一个。

由于

1 个答案:

答案 0 :(得分:6)

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