似乎每个 UserId 在 UserLogin 中有多个匹配项,您必须优先考虑 UserLogin 中给定 UserId 的记录,并在结果集中选择您想要的记录:
SELECT [USER].UserName , x.AttemptDate , .LogoutDate
FROM [User]
LEFT JOIN
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY <PriorityCondition>) Priority
FROM UserLogin
) x
ON [User].UserId = x.UserId AND x.Priority = 1
WHERE [User].TenantId=3
ORDER BY x.LogoutDate desc
就像在这个例子中一样:
DECLARE @User TABLE (UserId INT, UserName VARCHAR(100), TenantId INT)
INSERT @User VALUES (1, 'a', 3), (2, 'b', 3)
DECLARE @UserLogin TABLE (UserId INT, UserName VARCHAR(100), AttemptDate DATETIME, LogoutDate DATETIME)
INSERT @UserLogin VALUES (1, 'a', GETDATE(), GETDATE()),
(2, 'b', GETDATE(), GETDATE()),
(2, 'b', GETDATE(), DATEADD(DAY, -1, GETDATE()))
SELECT y.UserName , x.AttemptDate , x.LogoutDate
FROM @User y
LEFT JOIN
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY LogoutDate DESC) Priority
FROM @UserLogin
) x
ON y.UserId = x.UserId AND x.Priority = 1
WHERE y.TenantId=3
ORDER BY x.LogoutDate DESC