我的表结构是:
CREATE TABLE `survey` (
`id` int(11) NOT NULL auto_increment,
`submitdate` datetime default NULL,
`answer` varchar(5) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=499 ;
此处answer
包含诸如a1,a2,a3等值。
我想根据答案计算最近10天的记录。是否在某一天没有记录,它应该为零。
我想要的输出是
date count answer
19-11-2012 10 a1
19-11-2012 8 a2
19-11-2012 0 a3
18-11-2012 30 a1
18-11-2012 30 a2
18-11-2012 30 a3
我使用了像
这样的查询SELECT days.day, count(survey.id)
FROM
(select curdate() as day
union select curdate() - interval 1 day
union select curdate() - interval 2 day
union select curdate() - interval 3 day
union select curdate() - interval 4 day
union select curdate() - interval 5 day
union select curdate() - interval 6 day
union select curdate() - interval 7 day
union select curdate() - interval 8 day
union select curdate() - interval 9 day) days
left join survey
on days.day = date(survey.submitdate)
group by
days.day
答案 0 :(得分:0)
您可以使用SUBDATE功能回顾10天,并使用'>'比较日期。您还希望GROUP BY以及当天,因为您正在尝试计算每天每个答案的计数。
SELECT DATE(submitdate) AS day
answer,
COUNT(*) AS answer_count
FROM survey
WHERE DATE(submitdate) > DATE(SUBDATE(CURRENT_DATE, 10))
GROUP BY day, answer;