MySQL creates a 12-month date view

Time:2021-1-13

Create a 12-month view of this year:

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `root`@`%` 
    SQL SECURITY DEFINER
VIEW `year_month_view` AS
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-01') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-02') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-03') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-04') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-05') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-06') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-07') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-08') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-09') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-10') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-11') AS date UNION
SELECT CONCAT(DATE_FORMAT((CURDATE()), '%Y'),'-12') AS date 

Create a view for the first 12 months of the current month:

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `root`@`%` 
    SQL SECURITY DEFINER
VIEW `year_month_view` AS
    SELECT DATE_FORMAT(CURDATE(), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 1 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 2 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 3 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 4 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 5 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 6 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 7 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 8 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 9 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 10 MONTH), '%Y-%m') AS `year_month` 
    UNION SELECT DATE_FORMAT((CURDATE() - INTERVAL 11 MONTH), '%Y-%m') AS `year_month`