如何在MySQL中按月排序

时间:2012-11-02 05:46:18

标签: mysql sql-order-by

Here is demo

订单是11月和10月。如何为此添加ORDER BY,以便订单按月,1月,2月,3月等等。

提前致谢。

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` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=55 ;

--
-- Dumping data for table `hw_homework`
--

INSERT INTO `hw_homework` (`id`, `studentid`, `subjectid`, `assignment_name`, `teacherid`, `date`) VALUES
(52, 56, 13, '1A', 20, '2012-10-28'),
(53, 56, 6, '12', 18, '2012-10-28'),
(54, 56, 4, 'page42', 59, '2012-11-02');


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

7 个答案:

答案 0 :(得分:6)

正如Chuidiang建议我添加以下内容以获得我想要的东西。 谢谢大家。

ORDER BY Month(date)

答案 1 :(得分:2)

在查询中使用以下内容

GROUP BY MONTH(date)

答案 2 :(得分:2)

在您的情况下,它是基于字母排序。 以下将给出正确的结果。

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

答案 3 :(得分:1)

偶然发现这篇文章试图找到按月名排序的解决方案。可能不是非常优雅的解决方案,但您可以使用FIELD字符串函数来获取该结果集。

SELECT
studentID,
DATE_FORMAT(`date`, '%M') `month`,
COUNT(studentid) totalMissed FROM
hw_homework WHERE
studentid = 56 GROUP BY
studentid, 
DATE_FORMAT(`date`, '%M') ORDER BY
FIELD(
    DATE_FORMAT(`date`, '%M'),
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
);

试试吧。另外,为了便于阅读,您可以使用更简单的函数MONTHNAME(date)替换DATE_FORMAT。

答案 4 :(得分:0)

 SELECT  studentID, 
    DATE_FORMAT(`date`,'%M') as `month`,
    COUNT(studentid) totalMissed
FROM hw_homework
WHERE studentid = 56
order by Month(month)
GROUP BY studentid, DATE_FORMAT(`date`, '%M')

答案 5 :(得分:0)

SELECT  studentID, 
        DATE_FORMAT(`date`,'%M') `month`,
        COUNT(studentid) totalMissed
FROM hw_homework
WHERE studentid = 56
GROUP BY MONTH(DATE) ASC

答案 6 :(得分:-1)

的MySQL> select * from hw_homework order by date asc; //增加订单

OR

的MySQL>从日期desc的hw_homework顺序中选择*;