我们说我有一张没有数据的表。
该表格包含entry_date
列。
我将提供两个日期,如"2017-06-14","2017-06-18"
。
我想为每个日期选择存在的行数,如
count | entry_date
------------
0 | 2017-06-14
0 | 2017-06-15
0 | 2017-06-16
0 | 2017-06-17
0 | 2017-06-18
*表可能没有特定日期的条目,因此它应该在该日期返回0
答案 0 :(得分:2)
如下面的代码所示。您可以创建日历表。我们根据需要为我们提供准确的日历。 进入该日历表。
DROP TABLE IF EXISTS time_dimension;
CREATE TABLE time_dimension (
id INTEGER PRIMARY KEY, -- year*10000+month*100+day
db_date DATE NOT NULL,
year INTEGER NOT NULL,
month INTEGER NOT NULL, -- 1 to 12
day INTEGER NOT NULL, -- 1 to 31
quarter INTEGER NOT NULL, -- 1 to 4
week INTEGER NOT NULL, -- 1 to 52/53
day_name VARCHAR(9) NOT NULL, -- 'Monday', 'Tuesday'...
month_name VARCHAR(9) NOT NULL, -- 'January', 'February'...
holiday_flag CHAR(1) DEFAULT 'f' CHECK (holiday_flag in ('t', 'f')),
weekend_flag CHAR(1) DEFAULT 'f' CHECK (weekday_flag in ('t', 'f')),
event VARCHAR(50),
UNIQUE td_ymd_idx (year,month,day),
UNIQUE td_dbdate_idx (db_date)
) Engine=MyISAM;
DROP PROCEDURE IF EXISTS fill_date_dimension;
DELIMITER //
CREATE PROCEDURE fill_date_dimension(IN startdate DATE,IN stopdate DATE)
BEGIN
DECLARE currentdate DATE;
SET currentdate = startdate;
WHILE currentdate < stopdate DO
INSERT INTO time_dimension VALUES (
YEAR(currentdate)*10000+MONTH(currentdate)*100 + DAY(currentdate),
currentdate,
YEAR(currentdate),
MONTH(currentdate),
DAY(currentdate),
QUARTER(currentdate),
WEEKOFYEAR(currentdate),
DATE_FORMAT(currentdate,'%W'),
DATE_FORMAT(currentdate,'%M'),
'f',
CASE DAYOFWEEK(currentdate) WHEN 1 THEN 't' WHEN 7 then 't' ELSE 'f' END,
NULL);
SET currentdate = ADDDATE(currentdate,INTERVAL 1 DAY);
END WHILE;
END
//
DELIMITER ;
TRUNCATE TABLE time_dimension;
CALL fill_date_dimension('2000-01-01','2018-01-01');
创建该日历表后,您可以在下面写下查询,它将解决您的问题。
SELECT COUNT(datetime) ,DB_DATE FROM time_dimension TD
LEFT JOIN YOUR_TABLENAME TN ON DATE(TN.entry_date)=TD.db_date
WHERE TD.DB_DATE BETWEEN '2017-06-14' AND '2017-06-18'
GROUP BY DATE(DB_DATE);
希望这会有所帮助。