开发者

SQL Query to get Average time

I have 4 columns in my database

UserName, Date, Time, LoginType

UserName is a varchar field
Date is a date field
Time is a time field (in 24 hour format)
LoginType is a varchar field

LoginType can contain one of the two strings "LOGIN", "SHUTDOWN"

I want to get the average time someone will LOGIN or SHUTDOWN I also want to know the del开发者_运维知识库ta of the lateless, earliness.

So for this example, lets assume that students must attent class by 8:30 and must LOGOFF by 10:30

So lets also assume the sample data is as follows

George.Lucas 8:45 2011-07-22 LOGIN
Eric.TheRed 9:00 2011-07-22 LOGIN
Dr.Who 9:01 2011-07-22 LOGIN
Dr.Who 11:01 2011-07-22 SHUTDOWN
George.Lucas 11:45 2011-07-22 SHUTDOWN
Eric.TheRed 12:00 2011-07-22 SHUTDOWN
  1. We can see that George was 15 min late and he shutdown 1hr 15min late
  2. Eric was 30 min late to login
  3. Eric was 2hr 30 min late to SHUTDOWN
  4. Dr.Who was 31 min late LOGIN
  5. Dr.Who was 31 min late SHUTDOWN

Thanks


This will give you the average time a given user took between login and shutdown, even when there are multiple sessions for the same day, and assuming the user needs to shutdown before logging in again:

SELECT login.UserName, 
  AVG(shutdown.Date - login.Date)
FROM table login,
  table shutdown
WHERE login.UserName = shutdown.UserName
      AND login.LoginType = 'LOGIN'
      AND shutdown.LoginType = 'SHUTDOWN'
      AND shutdown.Date = (SELECT MIN(t.Date)
                           FROM table t
                           WHERE t.UserName = login.UserName
                                 AND t.LoginType = 'SHUTDOWN'
                                 AND t.Date > login.Date)
GROUP BY login.UserName;

To find out the difference between the expected and effective login/shutdown time, you just need to subtract 8:30 and 10:30 from login.Time and shutdown.Time, respectively.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜