-1

我有以下 db 表,其中显示了错过的作业。

CREATE TABLE `missed_homework` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `studentid` int(10) NOT NULL,
  `subjectid` int(10) NOT NULL,
  `assignment_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `teacherid` int(10) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ... ;


INSERT INTO `missed_homework` (`id`, `studentid`, `subjectid`, `assignment_name`, `teacherid`, `date`) VALUES
(1, 29, 5, '5E', 20, '2012-10-18 13:58:40'),
(2, 15, 5, '32B', 20, '2012-10-18 13:59:54'),
(3, 29, 4, 'Q2A', 20, '2012-10-18 17:53:46'),
(4, 29, 11, '6E', 20, '2012-10-02 20:06:39'),
(5, 29, 11, 'C15', 20, '2012-10-16 20:06:30'),
(6, 15, 11, '7A', 20, '2012-09-19 20:08:05'),
(7, 29, 5, '3B', 20, '2012-09-14 20:08:12'),
(8, 29, 13, '6E', 32, '2012-10-18 20:23:46'),
(9, 29, 11, '7E', 18, '2012-10-20 14:35:14')......

我不确定如何执行以下操作。

  1. 我想通过按月分组的 studentid=29 来查找错过的作业总数。
  2. 与上述相同,但按周分组。

我尝试了以下操作,但它没有输出我想要的。

 $this->db->where('studentid',$id);
    $this->db->from('missed_homework');
    $this->db->group_by('date');
    $query=$this->db->get();
4

1 回答 1

2

我习惯于DATE_FORMAT()获取月份的名称和每个日期的周数。

以下是您的答案Question #1

SELECT  studentID, 
        DATE_FORMAT(`date`, '%M') `month`,
        COUNT(studentID) totalMissed
FROM hw_homework
-- WHERE studentID = ''
GROUP BY studentID, DATE_FORMAT(`date`, '%M')

SQLFiddle 演示

为了Question #2

SELECT  studentID, 
        DATE_FORMAT(`date`, '%U') `WeekNo`,
        COUNT(studentID) totalMissed
FROM hw_homework
-- WHERE studentID = ''
GROUP BY studentID, DATE_FORMAT(`date`, '%U')

SQLFiddle 演示

于 2012-10-20T06:39:40.243 回答