SQL使用MAX或TOP仅获取每行结果的一行

时间:2016-11-15 01:43:45

标签: sql get row

我有一个包含3个表的数据库:

  • 用户用户ID,用户名
  • 计算机 ComputerID,ComputerName
  • 登录 LogonDate,UserID,ComputerID

我使用以下查询尝试获取每台计算机的最新用户名和LogonDate。

SELECT MAX(LogonDate) AS LogonDate, ComputerName, Username 
FROM Users u, Computers c, Logons l 
WHERE u.UserID = l.UserID 
  AND c.ComputerID = l.ComputerID 
GROUP BY ComputerName, Username 
ORDER BY ComputerName

可以理解,它为每个用户提供了最新的登录信息。我想将它限制在最新的条目中。

请帮助:)
感谢

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT (select MAX(l.LogonDate) from users z where z.UserID = u.UserId) AS LogonDate, c.ComputerName, u.Username 
FROM Users u, Computers c, Logons l 
WHERE u.UserID = l.UserID AND c.ComputerID = l.ComputerID
GROUP BY c.ComputerName, u.Username
ORDER BY c.ComputerName

答案 1 :(得分:0)

首先,学习正确的JOIN语法。简单规则:从不FROM子句中使用逗号。所以基本的查询是:

SELECT l.LogonDate, c.ComputerName, u.Username
FROM Logons l JOIN
     Users u
     ON u.UserID = l.UserID JOIN
     Computers c
     ON c.ComputerID = l.ComputerID;

要获取最新的登录信息,请使用row_number()或类似条件:

SELECT l.LogonDate, c.ComputerName, u.Username
FROM Logons l JOIN
     Users u
     ON u.UserID = l.UserID JOIN
     Computers c
     ON c.ComputerID = l.ComputerID
WHERE l.LogonDate = (SELECT MAX(l2.LogonDate)
                     FROM Logons l2
                     WHERE l2.ComputerID = l.ComputerID
                    );