0

我有一个如下所示的 MySQL 表:

+--------+------------+------------------+
|   id   | account_id |     posted_at    |
+--------+------------+------------------+
|   1    |       1    | 2013-10-05 23:09 |
|   2    |       1    | 2013-10-07 14:24 |
|   3    |       1    | 2013-10-07 01:17 |
|   4    |       1    | 2013-10-09 06:58 |
+--------+------------+------------------+

对于一个特定的account_id(在本例中为 1),我想返回这个(对于当前月份的日期):

+--------+------------+
|  count |    date    |
+--------+------------+
|    0   | 2013-10-01 |
|    0   | 2013-10-02 |
|    0   | 2013-10-03 |
|    0   | 2013-10-04 |
|    1   | 2013-10-05 |
|    0   | 2013-10-06 |
|    2   | 2013-10-07 |
|    0   | 2013-10-08 |
|    1   | 2013-10-09 |
+--------+------------+

我有一个 SQL 查询,它返回本月内每个日期的 COUNTS。

SELECT 
    DATE(posted_at) AS formatted_date, 
    COUNT(id) AS count 
FROM entries 
WHERE account_id = 1 
    AND MONTH(DATE(posted_at)) = MONTH(NOW()) 
GROUP BY formatted_date 
ORDER BY formatted_date ASC

它只是返回这个:

+--------+------------+
|  count |    date    |
+--------+------------+
|    1   | 2013-10-05 |
|    2   | 2013-10-07 |
|    1   | 2013-10-09 |
+--------+------------+

当然,对于没有数据的日期,COUNT 不会返回任何内容。我希望结果对于没有数据的日期为零。

我读过您应该创建一个包含所有可能日期的连接表。这是唯一的方法吗?

4

1 回答 1

0

你可以试试这样的

Declare @INT DATETIME = null
SELECT COUNT( CASE WHEN @INT IS NOT NULL THEN @INT ELSE NULL END)

我不确定mysql,但在sql server中它会是这样的......

SELECT 
    DATE(posted_at) AS formatted_date, 
    COUNT( CASE WHEN IS NOT NULL THEN posted_at ELSE NULL END ) AS [count] 
FROM entries 
WHERE account_id = 1 
    AND MONTH(DATE(posted_at)) = MONTH(NOW()) 
GROUP BY formatted_date 
ORDER BY formatted_date ASC
于 2013-10-09T18:57:39.017 回答