MySQL:每个日期出现的组

时间:2016-01-05 17:20:08

标签: php mysql sql count group-by

我想这是一个反复出现的问题,但我找不到正确的话题,指出我正确的方向。

我有聊天表,看起来很像:

+---------+----------------+---------------------+-----------------+
| id(int) | author(string) |   date(datetime)    | message(string) |
+---------+----------------+---------------------+-----------------+
|       1 | John           | 2016-01-01 17:18:00 | I               |
|       2 | Mary           | 2016-01-01 14:22:00 | Just            |
|       3 | John           | 2016-01-01 09:02:00 | Want            |
|       4 | John           | 2016-01-02 17:18:00 | To              |
|       5 | Mary           | 2016-01-03 18:26:00 | Say             |
|       6 | John           | 2016-01-03 10:42:00 | Hello           |
+---------+----------------+---------------------+-----------------+

我想得到什么:

+------------+------+------+
|    day     | Mary | John |
+------------+------+------+
| 2016-01-01 |    1 |    2 |
| 2016-01-02 |    0 |    1 |
| 2016-01-03 |    1 |    1 |
+------------+------+------+

我是否有义务在 COUNT 声明中执行子查询?

到目前为止,我提出了:

SELECT DATE(date) as day,
(SELECT COUNT(id) FROM chat WHERE author = 'Mary') AS 'Mary'
(SELECT COUNT(id) FROM chat WHERE author = 'John') AS 'John'
FROM chat
GROUP BY day
ORDER BY day ASC

但是这给了我每行作者的总消息数:

+------------+------+------+
|    day     | Mary | John |
+------------+------+------+
| 2016-01-01 |    2 |    4 |
| 2016-01-02 |    2 |    4 |
| 2016-01-03 |    2 |    4 |
+------------+------+------+

非常感谢任何相关主题的帮助或链接。 祝你有个美好的一天

2 个答案:

答案 0 :(得分:2)

只需使用条件聚合:

SELECT DATE(date) as day,
       SUM(author = 'Mary') AS Mary,
       SUM(author = 'John') AS John
FROM chat
GROUP BY day
ORDER BY day ASC

答案 1 :(得分:1)

我可能错了,但它会像我一样寻找一个解决方案,在那里你有一小群相同的用户?即使这是真的,我也会改变逻辑,以避免生成查询并为大量用户带来问题。它可能不是您当前问题的完美解决方案,但可能有助于节省一些时间。所以我会使用不同的模式。

作为查询,我会使用这样的东西:

SELECT DATE(`date`) AS day,
  `author`,
  COUNT(`id`) AS messagecount
FROM `chat`
GROUP BY `day`, `author`
ORDER BY `day` ASC

有了这个,你会得到这样的结果:

+------------+--------+--------------+
|    day     | author | messagecount |
+------------+--------+--------------+
| 2016-01-01 | Mary   |            2 |
| 2016-01-01 | John   |            4 |
| 2016-01-02 | Mary   |            2 |
| 2016-01-02 | John   |            4 |
+------------+--------+--------------+

之后,您可以将结果分组为PHP以获得所需的效果,例如使用日期作为键生成这样的数组:

array(
  '2016-01-01' => array(
    'day' => '2016-01-01',
    'Mary' => 2,
    'John' => 4
  ),
  '2016-01-02' => array(
    'day' => '2016-01-02',
    'Mary' => 2,
    'John' => 4
  ),
)