简体   繁体   English

选择今年的月份MySql

[英]Select Months This Year MySql

I want to show all this year months (until today month). 我想显示今年的所有月份(直到今天一个月)。 For example, this is my desired result: 例如,这是我想要的结果:

MONTHS
Jan
Feb
Mar

Appreciate your help. 感谢您的帮助。 Thanks.. 谢谢..

Using the following leaves a month (as 1-12) that you can join against other fields: 使用以下命令可以留下一个月(截至1-12),您可以加入其他字段:

SELECT month, MONTHNAME(DATE_ADD(CONCAT(YEAR(NOW()),'-01-01'), INTERVAL month-1 MONTH)) as name_of_month
FROM (SELECT 1 month
             UNION ALL
             SELECT 2 month
             UNION ALL
             SELECT 3 month
             UNION ALL
             SELECT 4 month
             UNION ALL
             SELECT 5 month
             UNION ALL
             SELECT 6 month
             UNION ALL
             SELECT 7 month
             UNION ALL
             SELECT 8 month
             UNION ALL
             SELECT 9 month
             UNION ALL
             SELECT 10 month
             UNION ALL
             SELECT 11 month
             UNION ALL
             SELECT 12 month) m
 WHERE month <= MONTH(NOW())

While this is quite trivial in a programming language kind be a bit complex when attempting with mysql. 尽管在编程语言中这很简单,但是尝试使用mysql时却有些复杂。

You can look at the live code run here. 您可以在此处查看实时代码。 https://paiza.io/projects/zcABYyyM_uu3r2LX7cCmfQ https://paiza.io/projects/zcABYyyM_uu3r2LX7cCmfQ

DELIMITER //
CREATE PROCEDURE generate_months_upto_current_month()
BEGIN
    DECLARE month  INT;
    DECLARE inter  INT;
    DECLARE result  VARCHAR(25);

    DECLARE current_month  INT;

    SET month = 1;
    SET current_month = MONTH(CURRENT_DATE());

    WHILE month  <= current_month DO
        SET inter = current_month-month;
        SET result = MONTHNAME(DATE_SUB(CURRENT_DATE(), INTERVAL inter MONTH));
        SELECT SUBSTRING(result,1,3); -- to truncate to 3 letter months
        SET month = month + 1;
    END WHILE;
END //
DELIMITER ;


CALL generate_months_upto_current_month();

Since I am using loops I had to use a stored procedure. 由于我使用循环,因此必须使用存储过程。 I have mainly used mysql date functions to sort out the date interactions. 我主要使用mysql日期函数来整理日期交互。

Have a look at the following resource for details on Date functions 请查看以下资源以获取有关Date函数的详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM