从MAX记录计算DATEDIFF

时间:2016-07-29 14:56:19

标签: sql sql-server sql-server-2008-r2

使用SQL Server 2008 R2我试图将每天存储在表中的用户的最后登录时间拉到一起。

下面的查询为每个用户提取该信息:

SELECT 
    [Login_name],
    MAX([last_login_time]) as Last_login_date,
    [server_instance]
FROM 
    [dbo].[User_Login_Audit]
WHERE 
    Login_name NOT IN ('NT AUTHORITY\SYSTEM', 'sa','')
GROUP BY 
    Login_name, server_instance

结果如下:

User_name | 2016-07-28  | Server/Instance

我想要的是能够在最长记录日期的GETDATE()之间添加天数并将其添加为最后一列..

我已尝试使用以下代码,但它会返回为该用户记录的每一天的值。任何帮助都会受到赞赏,因为我确信我错过了一些明显的东西。

SELECT 
    [Login_name],
    MAX([last_login_time]) AS Last_login_date,
    [server_instance],
    DATEDIFF(day, getdate(), last_login_time) AS Days
FROM 
    [dbo].[User_Login_Audit]
WHERE
    Login_name NOT IN ('NT AUTHORITY\SYSTEM', 'sa','')
GROUP BY 
    Login_name, server_instance, last_login_time

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT [Login_name],
    max([last_login_time]) Last_login_date,
  [server_instance],
  DATEDIFF(day, getdate(), max([last_login_time])) Days
FROM [dbo].[User_Login_Audit]
where  Login_name not in ('NT AUTHORITY\SYSTEM', 'sa','')
Group by Login_name, server_instance

答案 1 :(得分:0)

 ;with cte
 as
( SELECT
 [Login_name]
 ,max([last_login_time]) as Last_login_date
 ,[server_instance],
 FROM [dbo].[User_Login_Audit]
  where  Login_name not in ('NT AUTHORITY\SYSTEM', 'sa','')
Group by Login_name,server_instance
 )
select *,
 DATEDIFF(day,getdate(),Last_login_date)
from cte

答案 2 :(得分:0)

    SELECT 
    u1.[Login_name],
    u1.[server_instance],
    COALESCE(MAX(u2.[last_login_time]),'No previous') AS Last_login_date,
    COALESCE(DATEDIFF(day, getdate(), MAX(u2.last_login_time)), 'No previous') AS Days
FROM 
    [dbo].[User_Login_Audit] ua1
    LEFT JOIN [dbo].[User_Login_Audit] ua2 ON ua1.[Login_name] = ua2.[Login_name] and 
                                                ua1.[server_instance] = ua2.[server_instance] and 
                                                u1.[last_login_time] > u2 .[last_login_time]
WHERE
    u1.Login_name NOT IN ('NT AUTHORITY\SYSTEM', 'sa','')
GROUP BY 
    u1.Login_name, u1.server_instance