0

我在网站上有一个活动日志表。每次登录都有日期/时间、用户 ID 和 IP 地址列。

我想检索唯一用户名列表和他们登录的最新 IP 地址。

在 SQL Server 上使用 t-sql 从表中检索它的最佳方法是什么?

4

3 回答 3

2

一种可移植的方法是:

select l.userID, l.Date, l.IpAddress
from (
    select userID, max(Date) as MaxDate
    from Log
    group by userID
) lm
inner join Log l on lm.userID = l.userID
    and lm.MaxDate = l.Date

如果您有 SQL Server 2005+,您还可以执行以下操作:

select * from
(
    select userID, Date, IpAddress,  
        Rank() over (Partition BY userID order by Date DESC) as Rank
    from Log
) tmp
where Rank = 1
于 2012-04-17T16:12:26.510 回答
1

我在这里猜测一些列/表名,并且我假设用户名来自一个表(并且您不会每次都将用户名存储在日志中):

;WITH x AS
(
  SELECT userID, IPaddress, rn = ROW_NUMBER() OVER
  (PARTITION BY UserID ORDER BY datetimecolumn DESC)
  FROM dbo.LogTable
)
SELECT u.username, x.IPAddress
FROM x INNER JOIN dbo.Users AS u
ON u.userID = x.userID
WHERE x.rn = 1;
于 2012-04-17T16:15:44.933 回答
0
select distinct(user_name), (select top 1 IP_address from log_table where user_name=LOG.user_name order by log_date desc)
from log_table LOG
于 2012-04-17T16:18:32.403 回答