我在mysql上运行以下查询
SELECT DATE(field) AS day, COUNT( * ) AS totalSessions
FROM table
GROUP BY DATE(field)
ORDER BY field DESC
LIMIT 7
返回
day | totalSessions
2013-12-17 | 5
2013-12-15 | 1
我需要更改我的查询以便获得结果
day | totalSessions
2013-12-17 | 5
2013-12-16 | 0
2013-12-15 | 1
2013-12-14 | 0
2013-12-13 | 0
2013-12-12 | 0
2013-12-11 | 0
答案 0 :(得分:2)
您可能需要存储(某处)要返回的日期。我认为存储过程可以帮助您:
delimiter $$
create procedure getStuff(d0 date, d1 date)
begin
declare d date;
drop table if exists temp_dates;
create temporary table temp_dates (
d date not null primary key
);
set d = d0;
while d <= d1 do
insert into temp_dates values (d);
set d = date_add(d, interval +1 day);
end while;
select
a.d as day,
count(b.field) as totalSessions
from
temp_dates as a
left join yourTable as b on a.d = b.dateField -- Assuming "dateField" holds the date
group by
a.d;
end $$
delimiter ;
希望这有帮助
答案 1 :(得分:1)
不是最好看的解决方案,但值得一试:
SELECT
FAKE.dt,
COUNT(YT.id) AS totalSessions
FROM (
SELECT DATE(NOW()) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 2 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 3 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 4 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 5 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 6 DAY)) as dt
) FAKE
LEFT JOIN yourtable YT ON YT.datefield = FAKE.dt
GROUP BY FAKE.dt
ORDER BY FAKE.dt DESC
所以你从今天开始向后选择7个日期,结合结果,左边加入你需要的数据,分组和按日期排序。