2

我有一个这样的事件表:

-----------------------------------------------------------
timestamp            |  station |  event_type   |  count
-----------------------------------------------------------
2013-02-22 01:00:00  |  1       |  log_in       |  -1
2013-02-22 01:05:00  |  1       |  alert        |  5
2013-02-22 01:08:00  |  1       |  alert        |  3
2013-02-22 01:10:00  |  1       |  log_out      |  -1
2013-02-22 01:30:00  |  2       |  log_in       |  -1
2013-02-22 01:31:00  |  2       |  alert        |  2
2013-02-22 01:35:00  |  2       |  log_out      |  -1
-----------------------------------------------------------

如何编写 SQL 来生成这样的报告:

--------------------------------------------------------------------------
station  | log_in               |  log_out               | count
--------------------------------------------------------------------------
1        | 2013-02-22 01:00:00  |  2013-02-22 01:10:00   | 8
2        | 2013-02-22 01:30:00  |  2013-02-22 01:35:00   | 2
--------------------------------------------------------------------------

基本上,我想总结登录和注销之间的警报。

有人可以指出我正确的方向吗?

更新:

JW 在下面的回答有效,但我在上表中犯了一个错误。对于警报事件,我不知道站号,所以表格应该如下所示。

-----------------------------------------------------------
timestamp            |  station |  event_type   |  count
-----------------------------------------------------------
2013-02-22 01:00:00  |  1       |  log_in       |  -1
2013-02-22 01:05:00  |  -1      |  alert        |  5
2013-02-22 01:08:00  |  -1      |  alert        |  3
2013-02-22 01:10:00  |  1       |  log_out      |  -1
2013-02-22 01:30:00  |  2       |  log_in       |  -1
2013-02-22 01:31:00  |  -1      |  alert        |  2
2013-02-22 01:35:00  |  2       |  log_out      |  -1
-----------------------------------------------------------
4

1 回答 1

2
SELECT  station, 
        MIN(timestamp) login,
        MAX(timestamp) logout,
        SUM(CASE WHEN count > 0 THEN count ELSE 0 END) count
FROM    tbaleName
GROUP   BY station

更新 1

SELECT  a.station, 
        a.login,
        a.logout,
        SUM(CASE WHEN count > 0 THEN count else 0 END) count
FROM
        (
          SELECT  station, 
                  MIN(timestamp) login,
                  MAX(timestamp) logout
          FROM    tableName2 
          GROUP   BY station
        ) a
        INNER JOIN tableName2 b
          ON b.timestamp BETWEEN a.logIN and a.logout AND
             a.station <> -1
GROUP   BY a.station, 
           a.login,
           a.logout

为了获得更快的性能,请添加一个INDEXon 列timestamp

于 2013-02-22T08:02:02.670 回答