即使没有特定日期的数据,mysql日期列表也会计数

时间:2012-10-06 15:30:16

标签: mysql database gaps-and-islands

  

可能重复:
  MySQL how to fill missing dates in range?

我正在尝试从mysqldata制作图表,

Postid | date       | text
1      | 2012-01-01 | bla
2      | 2012-01-01 | bla
3      | 2012-01-02 | bla
4      | 2012-01-02 | bla
5      | 2012-01-04 | bla
6      | 2012-01-04 | bla
7      | 2012-01-05 | bla

现在,我想获得每天的帖子数量,包括零日期。例如,我希望能够像这样得到第一周:

date       | count(Postid)
2012-01-01 | 2
2012-01-02 | 2
2012-01-03 | 0
2012-01-04 | 2
2012-01-05 | 1
2012-01-06 | 0
2012-01-07 | 0

我正在寻找一个通用的解决方案,我不需要指定每个日期。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

假设您的postid在您的表格中是连续的,那么此查询:

SELECT
  DATE_FORMAT(b.date, '%Y-%m-%d') date,
  COUNT(c.postid)
FROM
(
  SELECT
    (SELECT MAX(date) FROM ex) + INTERVAL 3 DAY - INTERVAL a.postid DAY AS date
  FROM
    ex a
) b
LEFT JOIN
  ex c ON c.date = b.date
GROUP BY
  b.date
ORDER BY
  b.date

产生

date    COUNT(c.postid)
2012-01-01  2
2012-01-02  2
2012-01-03  0
2012-01-04  2
2012-01-05  1
2012-01-06  0
2012-01-07  0

请参阅http://sqlfiddle.com/#!2/2cf8d/2

如果postid不是连续的,那么您可以使用ids连续ID表:

SELECT
  DATE_FORMAT(b.date, '%Y-%m-%d') date,
  COUNT(c.postid)
FROM
(
  SELECT
    (SELECT MAX(date) FROM ex) + INTERVAL 3 DAY - INTERVAL a.id DAY AS date
  FROM
    ids a
) b
LEFT JOIN
  ex c ON c.date = b.date
GROUP BY
  b.date
ORDER BY
  b.date DESC
LIMIT 7

请参阅http://sqlfiddle.com/#!2/13035/1

答案 1 :(得分:2)

在MySQL中,我建议创建一个列出日期的Calendar表。然后你将加入那张桌子。与此类似:

CREATE TABLE Table1(`Postid` int, `date` datetime, `text` varchar(3));

INSERT INTO Table1(`Postid`, `date`, `text`)
VALUES
    (1, '2011-12-31 17:00:00', 'bla'),
    (2, '2011-12-31 17:00:00', 'bla'),
    (3, '2012-01-01 17:00:00', 'bla'),
    (4, '2012-01-01 17:00:00', 'bla'),
    (5, '2012-01-03 17:00:00', 'bla'),
    (6, '2012-01-03 17:00:00', 'bla'),
    (7, '2012-01-04 17:00:00', 'bla');

CREATE TABLE Table2(`date` datetime);

INSERT INTO Table2(`date`)
VALUES('2011-12-31 17:00:00'),
    ('2012-01-01 17:00:00'),
    ('2012-01-02 17:00:00'),
    ('2012-01-03 17:00:00'),
    ('2012-01-04 17:00:00'),
    ('2012-01-05 17:00:00'),
    ('2012-01-06 17:00:00'),
    ('2012-01-07 17:00:00'),
    ('2012-01-08 17:00:00');

select t2.date, count(postid)
from table2 t2
left join table1 t1
  on t2.date = t1.date
group by t2.date

请参阅SQL Fiddle with Demo