我已经达到了我所拥有的极少知识的极限。
我有一张包含防火墙日志数据的表。有一个名为action的列是'允许'或'已删除'我想输出摘要数据,因此我可以在gnuplot中绘制允许与删除的图表。我可以这样做以获得允许或拒绝的计数:
mysql> select date_format(timestamp,'%H:%i:%s') as timestamp, count(action) as denied from events where timestamp >= '2013-11-01 00:00:00' and timestamp <= '2013-11-01 01:00:00' and action='dropped' GROUP BY UNIX_TIMESTAMP(timestamp) DIV 300 limit 3;
+-----------+--------+
| timestamp | denied |
+-----------+--------+
| 00:00:35 | 165 |
| 00:05:07 | 124 |
| 00:10:07 | 57 |
+-----------+--------+
3 rows in set (6.80 sec)
或者允许这样做:
mysql> select date_format(timestamp,'%H:%i:%s') as timestamp, count(action) as allowed from events where timestamp >= '2013-11-01 00:00:00' and timestamp <= '2013-11-01 01:00:00' and action='allowed' GROUP BY UNIX_TIMESTAMP(timestamp) DIV 300 limit 3;
+-----------+---------+
| timestamp | allowed |
+-----------+---------+
| 00:00:00 | 2392 |
| 00:05:00 | 2310 |
| 00:10:00 | 2029 |
+-----------+---------+
3 rows in set (7.29 sec)
我想要的是这样的输出:
+-----------+--------+---------+
| timestamp | denied | allowed |
+-----------+--------+---------+
| 00:00:35 | 165 | 2392 |
| 00:05:07 | 124 | 2310 |
| 00:10:07 | 57 | 2029 |
+-----------+--------+---------+
我尝试了一个联盟,但似乎将数据混合在两列中:
mysql> select timestamp, count(action) as allowed from events where timestamp >= '2013-11-01 00:00:00' and timestamp <= '2013-11-01 00:59:59' union all select timestamp, count(action) as denied from events where timestamp >= '2013-11-01 00:00:00' and timestamp <= '2013-11-01 23:59:59' and action='dropped';
+---------------------+---------+
| timestamp | allowed |
+---------------------+---------+
| 2013-11-01 00:00:00 | 54254 |
| 2013-11-01 00:00:35 | 31788 |
+---------------------+---------+
2 rows in set (13.77 sec)
答案 0 :(得分:0)
试试这个:
SELECT date_format(TIMESTAMP, '%H:%i:%s') AS TIMESTAMP,
SUM(CASE WHEN action = 'dropped' THEN 1 ELSE 0 END)AS denied,
SUM(CASE WHEN action = 'allowed' THEN 1 ELSE 0 END)AS allowed
FROM events
WHERE TIMESTAMP >= '2013-11-01 00:00:00'
AND TIMESTAMP <= '2013-11-01 01:00:00'
GROUP BY UNIX_TIMESTAMP(TIMESTAMP) DIV 300 limit 3;
每次CASE WHEN验证为真时,这将为SUM 1,否则为0。这应该可以得到你想要的结果,就像GROUP BY一样,我不确定你在那里做什么,所以我把它保留原样。