1

要求:从提供的租户的UserLogin表中获取登录表中的所有用户+ 及其最新登录记录

当前查询

SELECT [USER].UserName , UserLogin.AttemptDate , UserLogin.LogoutDate
FROM [User] LEFT JOIN UserLogin 
ON [User].UserId = UserLogin.UserId 
WHERE  [User].TenantId=3 
ORDER BY UserLogin.LogoutDate desc

问题:重复用户名不明确

4

4 回答 4

4
SELECT
    a.UserName,
    c.AttemptDate,
    c.LogoutDate
FROM
    [User] a
LEFT JOIN
    (
        SELECT UserId, MAX(LogoutDate) AS maxdate
        FROM UserLogin
        GROUP BY UserId
    ) b ON a.UserId = b.UserId
LEFT JOIN
    UserLogin c ON b.UserId = c.UserId AND b.maxdate = c.LogoutDate
WHERE
    a.TenantId = 3
ORDER BY
    c.LogoutDate DESC

此查询具有与 DBMS 无关的额外优势(除了 周围的括号User),并且不依赖于窗口函数或外部变量。

于 2012-07-06T08:31:23.507 回答
2

似乎每个 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
于 2012-07-06T08:22:42.353 回答
1
with cte as(
SELECT [USER].UserId , max(UserLogin.LogoutDate ) [LogoutDate]
FROM [User] JOIN UserLogin 
ON [User].UserId = UserLogin.UserId 
WHERE  [User].TenantId=3 
group by [USER].UserId 
 )
 select U.UserName,L.AttemptDate , L.LogoutDate from cte C , UserLogin L,
 [User] U
 where C.LogoutDate=L.LogoutDate
 and C.UserId=L.UserId
 and U.UserId=L.UserId
于 2012-07-06T08:40:18.473 回答
0

如果我理解正确

SELECT [USER].UserName , UserLogin.AttemptDate , MAX(UserLogin.LogoutDate) FROM [User] LEFT JOIN UserLogin  ON [User].UserId = UserLogin.UserId  WHERE  [User].TenantId=3 ORDER BY UserLogin.LogoutDate desc 
于 2012-07-06T08:21:08.060 回答