我的MySQL查询有点麻烦
这是我的结构:
select * from servers group by host;
+-----+----------------------+---------+---------------------+
| id | host | players | time |
+-----+----------------------+---------+---------------------+
| 1 | 28.167.243.83:27035 | 3 | 2016-12-12 21:03:33 |
| 3 | 78.17.183.116:27015 | 10 | 2016-12-12 21:03:33 |
| 63 | 208.147.243.91:27025 | 1 | 2016-12-12 21:56:01 |
| 115 | 208.147.243.83:27035 | 2 | 2016-12-12 22:30:02 |
| 118 | 206.147.243.83:27035 | 2 | 2016-12-12 22:32:02 |
| 121 | 204.147.243.83:27035 | 2 | 2016-12-12 22:34:01 |
| 124 | 203.147.243.83:27035 | 2 | 2016-12-12 22:36:01 |
| 127 | 202.147.243.83:27035 | 2 | 2016-12-12 22:38:01 |
| 130 | 201.147.243.83:27035 | 2 | 2016-12-12 22:40:01 |
| 133 | 208.147.243.83:27035 | 2 | 2016-12-12 22:42:02 |
+-----+----------------------+---------+---------------------+
结果一直在进行,因为每个主机每5分钟就有一个新条目。
我希望它看起来像这样:
除了第二列应该如下:
unique date;max players on that unique date
用逗号分隔每个唯一的日期到最大玩家设置
如何通过查询实现此目的?
屏幕截图查询:
SELECT host, TRIM(TRAILING ',' FROM GROUP_CONCAT(DISTINCT CONCAT(UNIX_TIMESTAMP(`time`) * 1000, ',', players) ORDER BY `time` ASC SEPARATOR ';')) AS datapoints FROM servers where `time` between date_sub(now(),INTERVAL 8 WEEK) and now() GROUP BY `host`
答案 0 :(得分:1)
试试这个:
SELECT
`host`,
GROUP_CONCAT(CONCAT(`day`,';',`max_players`)) as `info`
FROM (SELECT
`host`,
DATE_FORMAT(`time`,'%Y-%m-%d') as `day`,
MAX(`players`) as `max_players`
FROM `so_test_servers`
GROUP BY `host`, `day`) as A
GROUP BY `host`
答案 1 :(得分:0)
如果您希望用逗号连接的列,您可以编写GROUP BY
查询并将其包装到另一个查询中,例如:
SELECT a.host, CONCAT(a.`date`, ';', a.max_players)
FROM (
SELECT
`host`,
DATE_FORMAT(`time`,'%Y-%m-%d') as `date`,
MAX(`players`) as 'max_players'
FROM servers
GROUP BY host, `date`
) a;