2012-11-02 41 views
0

Here is demo如何通過一個月在MySQL

排序順序在11月。我怎樣才能把ORDER BY添加到這裏,以便按月,Jan,Feb,Mar ...等等。

在此先感謝。

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') 
+0

爲什麼不只是*按日期順序升序*? –

+3

您是否嘗試過「MONTH(日期)訂購」? – Chuidiang

回答

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') 
2

用作查詢如下

GROUP BY MONTH(date) 
-1

的mysql> SELECT * FROM日期ASC hw_homework秩序; //增加的順序

OR

的MySQL> SELECT * FROM按日期降序hw_homework順序;

+1

你還沒有明白要問什麼。查看其他答案以瞭解更多信息。 –

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

由於Chuidiang建議我添加以下來獲得我想要的。 謝謝大家。

ORDER BY Month(date) 
1

在你的情況下,它是基於aplhabets進行排序。 以下將給出正確的結果。

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') 
0

偶然發現這篇文章試圖找到按月份排序的解決方案。可能不是很優雅的解決方案,但您可以使用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。