sql查询更改维度表

时间:2016-03-16 02:49:03

标签: mysql sql

我有一个表:这与用户登录频率的日志相同

╔════════════╦═══════╦═════════════╗
║ month-year ║ user  ║ count_login ║
╠════════════╬═══════╬═════════════╣
║ 01-2016    ║ admin ║          12 ║
║ 01-2016    ║ user1 ║          10 ║
║ 02-2016    ║ admin ║           5 ║
║ 03-2016    ║ admin ║          15 ║
╚════════════╩═══════╩═════════════╝

可能会改为

╔════════════╦═══════╦═══════╗
║ month-year ║ admin ║ user1 ║
╠════════════╬═══════╬═══════╣
║ 01-2016    ║    12 ║    10 ║
║ 02-2016    ║     5 ║     0 ║
║ 03-2016    ║    15 ║     0 ║
╚════════════╩═══════╩═══════╝

如果可能的话,我可以使用什么查询?

1 个答案:

答案 0 :(得分:0)

使用Conditional Aggregate执行此操作

select `month-year`, 
       sum(case when user = 'admin' then count_login else 0 end) as admin,
       sum(case when user = 'user1' then count_login else 0 end) as user1
From yourtable
Group by `month-year`

检查此答案是否有动态旋转:MySQL pivot row into dynamic number of columns