使用不存在访问SQL查询帮助

时间:2011-02-09 20:22:20

标签: sql ms-access

我有一个名为sys_event_log的表,其中包含以下列:

USER_NAME, 事件类型, EVENT_MESSAGE, TIME_STAMP

使用“登录成功”或“退出事件”的event_type跟踪登录和注销事件

在Access中使用SQL我试图在事件日志event_types和time_stamps上返回已登录数据库但尚未根据严格注销的不同用户列表。

到目前为止我提出的查询是:

SELECT DISTINCT
     a.user_name,
     a.event_type,
     a.time_stamp
FROM
     sys_event_log a
WHERE NOT EXISTS
 (
     SELECT
          1
     FROM
          sys_event_log b
     WHERE
          b.time_stamp > a.time_stamp 
          AND a.user_name = b.user_name 
          AND a.event_type = "Logout Event"
 )
AND a.event_type = "Login Success";

感觉很接近,但没有返回预期的数据集。

3 个答案:

答案 0 :(得分:1)

如果你使用

会更有意义
b.event_type = "Logout Event"

这里

      b.time_stamp > a.time_stamp 
      AND a.user_name = b.user_name 
      AND a.event_type = "Logout Event"

答案 1 :(得分:1)

试试这个:

SELECT 
   a.user_name, 
   a.event_type, 
   a.time_stamp
FROM
   sys_event_log a
WHERE a.event_type = "Login Success" AND
   a.time_stamp = ( SELECT MAX( b.time_stamp ) 
                    FROM sys_event_log b 
                    WHERE b.user_name = a.user_name )

答案 2 :(得分:1)

  SELECT a.user_name
       , COUNT(*) AS logins
       , ( SELECT COUNT( b.time_stamp ) 
             FROM sys_event_log b 
             WHERE b.user_name = a.user_name
               AND b.event_type = "Logout Event"
          ) AS logouts
       , logins - logouts AS activeConnections
    FROM sys_event_log a
    WHERE a.event_type = "Login Success"
    GROUP BY a.user_name
    HAVING logins > logouts