ORDER月份表按当月

时间:2016-07-19 13:06:10

标签: mysql sql-order-by

我想在当月订购数月的最终位置。

我有一个子查询返回:

+-----+-----------+
| one | monthname |
+-----+-----------+
| 1   |   Jan     |
| 2   |   Feb     |
| 3   |   Mar     |
| 4   |   Apr     |
| ... |   ...     |
+-----+-----------+

然后我想命令它将当前月份(MONTH(NOW()))作为最后一个值。但我一直收到默认月份订单。

例如,今天,7月(第7个月),我想:

+-----+-----------+
| one | monthname |
+-----+-----------+
|  8  |   Aug     |
|  9  |   Sep     |
| 10  |   Oct     |
| 11  |   Nov     |
| 12  |   Dec     |
|  1  |   Jan     |
|  2  |   Feb     |
|  3  |   Mar     |
|  4  |   Apr     |
|  5  |   Mei     |
|  6  |   Jun     |
|  7  |   Jul     |
+-----+-----------+

是否可以在SQL查询中执行?如果是这样,最好的方法是什么?

修改

我目前的查询如下

SELECT `months`,
IFNULL(case_result.Total_rows,0) results 
FROM 
(SELECT `one`,`monthname` AS months FROM 
(SELECT 1 AS `one`, 'JANUARY' AS `monthname` 
UNION SELECT 2 AS `one`,'FEBURARY' AS `monthname` 
UNION SELECT 3 AS `one`, 'MARCH' AS `monthname` 
UNION SELECT 4 AS `one`, 'APRIL' AS `monthname` 
UNION SELECT 5 AS `one`, 'MAY' AS `monthname` 
UNION SELECT 6 AS `one`,'JUNE' AS `monthname` 
UNION SELECT 7 AS `one`,'JULY' AS `monthname` 
UNION SELECT 8 AS `one`, 'AUGUST' AS `monthname`
UNION SELECT 9 AS `one`, 'SEPTEMBER' AS `monthname` 
UNION SELECT 10 AS `one`, 'OCTOBER' AS `monthname` 
UNION SELECT 11 AS `one`, 'NOVEMBER' AS `monthname` 
UNION SELECT 12 AS `one`, 'DECEMBER' AS `monthname` order by ) AS month_table) tempmonths LEFT JOIN (SELECT MONTH(date_surgery) AS `month`, COUNT(id_cases) AS Total_Rows 
FROM cases 
WHERE date_surgery BETWEEN DATE_SUB(NOW(), INTERVAL 11 MONTH) AND NOW()
AND cases.name = 'Bone Tumor'
GROUP BY MONTH(`date_surgery`)) AS case_result ON tempmonths.one = case_result.month

但我需要订购的部分是这个子查询

SELECT 1 AS `one`, 'JANUARY' AS `monthname` 
    UNION SELECT 2 AS `one`,'FEBURARY' AS `monthname` 
    UNION SELECT 3 AS `one`, 'MARCH' AS `monthname` 
    UNION SELECT 4 AS `one`, 'APRIL' AS `monthname` 
    UNION SELECT 5 AS `one`, 'MAY' AS `monthname` 
    UNION SELECT 6 AS `one`,'JUNE' AS `monthname` 
    UNION SELECT 7 AS `one`,'JULY' AS `monthname` 
    UNION SELECT 8 AS `one`, 'AUGUST' AS `monthname`
    UNION SELECT 9 AS `one`, 'SEPTEMBER' AS `monthname` 
    UNION SELECT 10 AS `one`, 'OCTOBER' AS `monthname` 
    UNION SELECT 11 AS `one`, 'NOVEMBER' AS `monthname` 
    UNION SELECT 12 AS `one`, 'DECEMBER' AS `monthname` order by ...

1 个答案:

答案 0 :(得分:2)

如果one是包含月份编号的列的名称,只需将其添加到select语句中:

order by (one+11-month(now)) % 12

当前月份的表达式将为11,而对于所有其他月份,由于模运算符(%),它将会更少。