使用以下mysql查询:
SELECT DATE_FORMAT(time, '%Y-%m-%d') AS time,report,count(ip) AS countip FROM asn_data WHERE DATE_FORMAT(time, '%Y-%m-%d') > '2012-10-31' GROUP BY DATE_FORMAT(time,'%Y-%m-%d'),report;
我得到了以下输出:
+------------+---------------+---------+
| time | report | countip |
+------------+---------------+---------+
| 2012-11-01 | bots | 76 |
| 2012-11-01 | openresolvers | 97 |
| 2012-11-01 | proxy | 24 |
| 2012-11-01 | scanners | 4 |
| 2012-11-01 | spam | 881 |
| 2012-11-02 | bots | 142 |
| 2012-11-02 | proxy | 22 |
| 2012-11-02 | spam | 667 |
| 2012-11-03 | proxy | 1 |
+------------+---------------+---------+
获取以下输出的查询是什么:
+------------+-------------+---------------+-------+----------+------+
| time | bots | openresolvers | Proxy | scanners | spam |
+------------+-------------+---------------+-------+----------+------+
| 2012-11-01 | 76 | 97 | 24 | 4 | 881 |
| 2012-11-02 | 142 | 0 | 22 | 0 | 667 |
| 2012-11-03 | 0 | 0 | 1 | 0 | 0 |
+------------+-------------+---------------+-------+----------+------+
答案 0 :(得分:2)
这里不需要组concat,你需要透视结果集,尝试这样:
SELECT DATE_FORMAT(time, '%Y-%m-%d') AS time,
SUM(CASE WHEN report = 'bots' THEN ipc ELSE 0 END) AS bots,
SUM(CASE WHEN report = 'openresolvers' THEN ipc ELSE 0 END) AS openresolvers,
SUM(CASE WHEN report = 'Proxy' THEN ipc ELSE 0 END) AS Proxy,
SUM(CASE WHEN report = 'scanners' THEN ipc ELSE 0 END) AS scanners,
SUM(CASE WHEN report = 'spam' THEN ipc ELSE 0 END) AS spam
FROM (
SELECT count(ip) AS ipc, report, DATE(time) as time
FROM asn_data
GROUP BY report, DATE(time)) i
WHERE DATE_FORMAT(time, '%Y-%m-%d') > '2012-10-31'
GROUP BY time;
答案 1 :(得分:1)
SELECT DATE(time) AS time,
SUM(report='bots' ) AS bots,
SUM(report='openresolvers') AS openresolvers,
SUM(report='proxy' ) AS Proxy,
SUM(report='scanners' ) AS scanners,
SUM(report='spam' ) AS spam
FROM asn_data
WHERE time > '2012-10-31'
GROUP BY DATE(time)
在sqlfiddle上查看。
如果您希望排除ip IS NULL
的记录,请在每个AND ip IS NOT NULL
功能中添加SUM()
。