SQL查询计算其他条件的总发生次数 - SQL Server 2008

时间:2015-03-17 16:29:40

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

我有一个跟踪用户登录/注销活动的表。我正在尝试创建一个查询,该查询返回当天登录的总人数,并为表中的每一天返回一行。以下是我正在使用的表的示例:

enter image description here

以下是SQLFiddle:http://sqlfiddle.com/#!6/1a1a5b/1/0

它包含操作发生时间的时间戳,执行操作的人员的UserID以及操作本身的类型。 “LI”表示“登录”,“LO”表示“已登出”。

以下是查询首选结果的示例:

enter image description here

因此,有关此查询的一些注意事项:

  • 该查询只能确定当天“参加”的人数。
  • 如果唯一身份用户已登录当天,则仅计算ONCE
  • 如果他们在同一天登录并多次注销并不重要。它仍然只计算当天该用户的ONCE。
  • 时间戳字段会自动转换为零小时/分钟/秒的日期。

我很难找到处理此查询的最佳方法。这是我尝试过的一些事情但是我无法接近

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()部分应该比我做的容易得多。我不确定我哪里出错了。我能否对此有所了解?

提前感谢大家!

1 个答案:

答案 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
;