如何在MYSQL中按列值分隔此分组数据?

时间:2017-03-29 17:36:08

标签: mysql sql join group-by

我有一个包含以下结构的表:

SELECT * FROM logs WHERE data = "Map load" 
ORDER BY timestamp DESC LIMIT 5

user_id timestamp            data
3       2017-03-29 18:11:25  Map load
2       2017-03-29 18:10:11  Map load
5       2017-03-29 18:02:07  Map load
5       2017-03-29 17:48:03  Map load
3       2017-03-29 17:38:48  Map load

我希望按行间隔15分钟对行进行分组。 但是,我还需要通过user_id对此数据进行分段。

按间隔分组:

SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp)/900)*900) AS `Time`,
COUNT(*) AS `Map Load` FROM logs 
WHERE data = "Map load"
GROUP BY `Time` ORDER BY `Time` DESC LIMIT 3

Time                Map Load
2017-03-29 18:00:00 3
2017-03-29 17:45:00 1
2017-03-29 17:30:00 1

期望的结果布局:

Time                user_id=3 user_id=2 user_id=5
2017-03-29 18:00:00 1         1         1
2017-03-29 17:45:00 0         0         1
2017-03-29 17:30:00 1         0         0

我有其他60个用户,所以除了在15分钟间隔时间戳上为每个user_id加入此表的副本之外,还有另一种方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time,
    sum(user_id = 3) as User_id_3,
    sum(user_id = 2) as User_id_2,
    sum(user_id = 5) as User_id_5
from logs
where data = "Map load"
group by time
order by time desc LIMIT 3

如果您有更多用户,建议不要在SQL中使用 pivot 值,而应该使用应用程序代码:

select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time,
    user_id,
    count(*) as cnt
from logs l
join (
    select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time
    from logs
    group by time
    order by time desc limit 3
    ) t on FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) = t.time
where data = 'Map load'
group by time,
    user_id
order by time desc;