3

可能重复:
MySQL 如何在范围内填充缺失的日期?

我正在尝试从 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

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

4

2 回答 2

3

假设你postid的 s 在你的表中是连续的,那么这个查询:

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的 s 不连续,那么您可以使用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

于 2012-10-06T15:48:17.477 回答
2

in MySQL, I would suggest creating a Calendar table with the dates listed. Then you will join on that table. Similar to this:

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

See SQL Fiddle with Demo

于 2012-10-06T15:44:35.063 回答