如何在mysql中根据月份(6月到5月)对记录进行排序?

时间:2014-02-01 10:37:05

标签: mysql

我想显示从6月开始的记录,可以使用mysql。

我的桌子是

id    | subjects   |   from         |   to             |
______|____________|________________|__________________|
1     |   php      |   2013-01-01   |  2013-01-21      |
2     |   C        |   2013-12-01   |  2013-12-21      |
3     |   C++      |   2013-04-01   |  2013-04-21      |
4     |   C#       |   2013-06-01   |  2013-06-21      |
5     |   Mysql    |   2013-09-01   |  2013-09-21      |

结果如

    id    | subjects   |   from         |   to             |
    ______|____________|________________|__________________|
    1     |   C#       |   2013-06-01   |  2013-06-21      |
    2     |   Mysql    |   2013-09-01   |  2013-09-21      |
    3     |   C        |   2013-12-01   |  2013-12-21      |
    4     |   php      |   2013-01-01   |  2013-01-21      |
    5     |   C++      |   2013-04-01   |  2013-04-21      |

1 个答案:

答案 0 :(得分:2)

我在SQL Server中提供代码,你可以在MySQL中做同样的事情。

CREATE TABLE Author (
    BookID INT IDENTITY,
    AuthID INT,
    DAT DATETIME
)
GO

INSERT INTO Author VALUES(2, GETDATE())
INSERT INTO Author VALUES(2, GETDATE()-60)
INSERT INTO Author VALUES(2, GETDATE()-180)
INSERT INTO Author VALUES(2, GETDATE()-30)
INSERT INTO Author VALUES(2, GETDATE()-70)
INSERT INTO Author VALUES(2, GETDATE()-270)
INSERT INTO Author VALUES(2, GETDATE()-360)

SELECT datename(month, DAT) AS MonthName,
               Month(DAT) AS MonthNum,
               CASE WHEN Month(DAT)-6 >0 
                    THEN Month(DAT)-6 
                    ELSE Month(DAT)+6 
               END AS ReqOrder,
               * 
 FROM Author 
 ORDER BY 3

DROP TABLE Author

让我知道您的意见/结果。