我有一个跟踪用户登录/注销活动的表。我正在尝试创建一个查询,该查询返回当天登录的总人数,并为表中的每一天返回一行。以下是我正在使用的表的示例:
以下是SQLFiddle:http://sqlfiddle.com/#!6/1a1a5b/1/0
它包含操作发生时间的时间戳,执行操作的人员的UserID以及操作本身的类型。 “LI”表示“登录”,“LO”表示“已登出”。
以下是查询首选结果的示例:
因此,有关此查询的一些注意事项:
我很难找到处理此查询的最佳方法。这是我尝试过的一些事情但是我无法接近
SELECT
COUNT(*)
AS
TotalAttendance
FROM(
SELECT
[Timestamp],
COUNT(*)
FROM
Attendance
WHERE
Attendance.Timestamp>{ts '2015-01-01 00:00:00'}
AND
Attendance.Action = 'LI'
GROUP BY
[UserID]
)
GROUP BY
[Timestamp]
ORDER BY
[Timestamp]
ASC
这也是:
SELECT
[Timestamp],
COUNT(*) AS TotalAttendance
FROM
Attendance
WHERE
Attendance.Timestamp>{ts '2015-01-01 00:00:00'}
AND
Attendance.Action = 'LI'
GROUP BY
[UserID],
[Timestamp]
ORDER BY
[Timestamp]
ASC
最后:
SELECT
[Timestamp],
COUNT(*) AS TotalAttendance
FROM
Attendance
WHERE
Attendance.Timestamp>{ts '2015-01-01 00:00:00'}
AND
Attendance.Action = 'LI'
GROUP BY
[Timestamp],
[AgentLogin]
HAVING
COUNT(*) > 1
ORDER BY
[Timestamp]
ASC
我在哪里错了?我知道我还没有解决时间戳转换,但我认为COUNT()部分应该比我做的容易得多。我不确定我哪里出错了。我能否对此有所了解?
提前感谢大家!
答案 0 :(得分:2)
SELECT Cast("Timestamp" As date) As the_date
, Count(DISTINCT CASE WHEN "Action" = 'LI' THEN UserID END) As attendance
FROM Attendance
GROUP
BY Cast("Timestamp" As date)
ORDER
BY the_date
;
SELECT Cast("Timestamp" As date) As the_date
, Count(DISTINCT UserID) As attendance
FROM Attendance
WHERE "Action" = 'LI'
GROUP
BY Cast("Timestamp" As date)
ORDER
BY the_date
;