2

我想显示来自

Q1:每个学生只在最后一周。

Q2:每个学生只有最后一个月。

我怎样才能做到这一点?

一周的演示

一个月的演示

CREATE TABLE `hw_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 `hw_homework` (`id`, `studentid`, `subjectid`, `assignment_name`, `teacherid`, 
`date`) VALUES
(1, 29, 5, '5E', 20, '2012-11-04 13:58:40'),
(2, 15, 5, '32B', 20, '2012-11-04 13:59:54'),
(3, 29, 4, 'Q2A', 20, '2012-10-30 17:53:46'),
(4, 29, 11, '6E', 20, '2012-11-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-29 20:23:46'),
(9, 29, 11, '7E', 18, '2012-10-30 14:35:14'),
(10, 2, 5, '5E', 20, '2012-10-21 13:58:40'),
(11, 2, 5, '5E', 20, '2012-10-30 13:58:40'),
(12, 2, 5, '5E', 20, '2012-10-31 13:58:40');

这不适用于上周。它显示了本周的结果。

SELECT  studentID, 
        DATE_FORMAT(`date`, '%U') `WeekNo`,
        COUNT(studentID) totalMissed
FROM hw_homework he
WHERE DATE_FORMAT(`date`, '%U') = (SELECT MAX(DATE_FORMAT(NOW(), '%U')) FROM hw_homework hi WHERE hi.studentID = he.studentID)
-- AND studentID = ''
GROUP BY studentID, DATE_FORMAT(`date`, '%U')

这在上个月不起作用。这显示了本月的结果。

SELECT  studentID, 
        DATE_FORMAT(`date`, '%M') `Month`,
        COUNT(studentID) totalMissed
FROM hw_homework he
WHERE DATE_FORMAT(`date`, '%M') = (SELECT MAX(DATE_FORMAT(NOW(), '%M')) FROM hw_homework hi WHERE hi.studentID = he.studentID)
-- AND studentID = ''
GROUP BY studentID, DATE_FORMAT(`date`, '%M')

提前致谢。

4

1 回答 1

0

尝试从 weekNo 中减去 1:

SELECT  studentID, 
        DATE_FORMAT(`date`, '%U') `WeekNo`,
        COUNT(studentID) totalMissed
FROM hw_homework he
WHERE DATE_FORMAT(`date`, '%U') = 
(SELECT MAX(DATE_FORMAT(NOW(), '%U')-1) 
 FROM hw_homework hi 
 WHERE hi.studentID = he.studentID)
GROUP BY studentID, DATE_FORMAT(`date`, '%U')
于 2012-11-04T01:06:01.390 回答