1

I have this table from which I need to select visitors count by date.

CREATE TABLE `visitors` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` VARCHAR(32) NOT NULL,
  `browser` VARCHAR(500) NOT NULL,
  `version` VARCHAR(500) NOT NULL,
  `platform` ENUM('w','l','m') NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

I try this:

SELECT DATE(`date`) AS `date`, COUNT(*) AS `visitor`
FROM `visitors` WHERE (`date` >= (NOW() - INTERVAL 7 DAY))
GROUP BY `date`;

Which returns this:

date         visitor
2015-12-19    2
2015-12-22    5

But what I really want is this:

date         visitor
2015-12-17    0        // Make 0 for the day which is not present
2015-12-17    0        // Make 0 for the day which is not present
2015-12-18    0        // Make 0 for the day which is not present
2015-12-19    2
2015-12-20    0        // Make 0 for the day which is not present
2015-12-21    0        // Make 0 for the day which is not present
2015-12-22    5

If I try with unions and get dates with this it is not problem with example 1 week. But what can I do if I need 1 year?

zekel
  • 9,227
  • 10
  • 65
  • 96
maia bardavelidze
  • 383
  • 1
  • 3
  • 10

1 Answers1

1

Use the sequence Engine. So you can generate date without a table

https://mariadb.com/kb/en/mariadb/sequence/

MariaDB [mysql]> SELECT date(now() - INTERVAL seq DAY) FROM seq_0_to_6;
+--------------------------------+
| date(now() - INTERVAL seq DAY) |
+--------------------------------+
| 2015-12-22                     |
| 2015-12-21                     |
| 2015-12-20                     |
| 2015-12-19                     |
| 2015-12-18                     |
| 2015-12-17                     |
| 2015-12-16                     |
+--------------------------------+
7 rows in set (0.00 sec)

This will work without a other Engine. You only must have a table with more Records as Days. The count of Days backwards is the LIMIT.

SELECT compare_date , count(v.`date`)
FROM (
    SELECT DATE(now() - INTERVAL @nr:=@nr+1 DAY)  AS compare_date 
    FROM information_schema.COLUMNS, (SELECT @nr:=-1) AS tmp 
    LIMIT 7
    ) AS d
LEFT JOIN  `visitors` v ON v.`date` = compare_date
GROUP BY compare_date;

Please tell this works for you.

Bernd Buffen
  • 14,525
  • 2
  • 24
  • 39