-1

我的表结构是:

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
4

1 回答 1

0

您可以使用 SUBDATE 函数回顾 10 天,并使用“>”比较日期。您还需要按答案和日期分组,因为您正在尝试计算每天每个单独答案的计数。

SELECT DATE(submitdate) AS day
answer,
COUNT(*) AS answer_count
FROM survey
WHERE DATE(submitdate) > DATE(SUBDATE(CURRENT_DATE, 10))
GROUP BY day, answer;
于 2012-11-19T17:11:12.380 回答