MySQL按列分组,然后按另一列计数

时间:2015-06-04 23:40:46

标签: php mysql

我有一个超出我基本知识的具有挑战性的MySQL问题,我真的很感激任何帮助。

我目前有以下查询:

select users.userid, CAST(posts.time AS DATE) 
FROM users INNER JOIN posts ON users.post_id = posts.id

示例输出:

userid | CAST(posts.time AS DATE)    
1............2015-01-05    
2............2015-02-06    
2............2015-04-07   
2............2015-04-07    
3............2015-04-07
1............2015-02-06    
7............2015-01-05

userid可以自行重复,可能有10个不同的行,userid = 1;同样适用于日期列。我想计算每个用户标识每个不同日期的行数。根据以上数据,输出应为:

-----------------------1----------2--------3---------4--------5--------6-------7
2015-01-05.............1..........0........0.........0........0........0.......1
2015-02-06.............1..........1........0.........0........0........0.......0
2015-04-07.............0..........2........1.........0........0........0.......0

我共有7个用户。我想用我定义的名称进一步替换用户ID;例如我会在标题/标题中定义1以显示为Mike,2将显示为George,依此类推......

有可能吗?谢谢大家。

2 个答案:

答案 0 :(得分:1)

如果您只有7个用户,并且只有永远,那么转动数据并不困难:

select date(posts.time),
       count(case when userid = 1 then userid end) as `1`,
       count(case when userid = 2 then userid end) as `2`,
       count(case when userid = 3 then userid end) as `3`,
       count(case when userid = 4 then userid end) as `4`,
       count(case when userid = 5 then userid end) as `5`,
       count(case when userid = 6 then userid end) as `6`,
       count(case when userid = 7 then userid end) as `7`
users INNER JOIN posts ON users.post_id = posts.id
group by date(posts.time)

demo here

如果您的用户数量多变或容易发生变化 - 这会变得很烦人,您最好选择应用程序语言来处理它。

答案 1 :(得分:0)

这就是我所拥有的(我没有为你完成):

SELECT date, SUM(id_1) AS Mike, SUM(id_2) AS George FROM (SELECT CASE id WHEN 1 THEN 1 ELSE 0 END as id_1, CASE id WHEN 2 THEN 1 ELSE 0 END as id_2, date FROM test_dates) as tmp GROUP BY date;

+------------+------+--------+
| date       | Mike | George |
+------------+------+--------+
| 2015-01-05 |    1 |      0 |
| 2015-02-06 |    1 |      1 |
| 2015-04-07 |    0 |      2 |
+------------+------+--------+

当你想要的是一个计数时,用一个1的总和代替的技巧是一个值得记住的常见报告技巧。我第一眼看到它时就流下了脑袋。