How to get first day of every corresponding month in mysql?

后端 未结 13 1786
野的像风
野的像风 2020-11-27 18:03

I want to get first day of every corresponding month of current year. For example, if user selects \'2010-06-15\', query demands to run from \'2010-06-01\' instead of \'2010

相关标签:
13条回答
  • 2020-11-27 18:43

    You can use EXTRACT to get the date parts you want:

    EXTRACT( YEAR_MONTH FROM DATE('2011-09-28') )
    -- 201109
    

    This works well for grouping.

    0 讨论(0)
  • 2020-11-27 18:44

    This is old but this might be helpful for new human web crawlers XD

    For the first day of the current month you can use:

    SELECT LAST_DAY(NOW() - INTERVAL 1 MONTH) + INTERVAL 1 DAY;
    
    0 讨论(0)
  • 2020-11-27 18:48
    SELECT LAST_DAY(date) as last_date, DATE_FORMAT(date,'%Y-%m-01') AS fisrt_date FROM table_name
    

    date=your column name

    0 讨论(0)
  • 2020-11-27 18:51

    use date_format method and check just month & year

    select * from table_name where date_format(date_column, "%Y-%m")="2010-06"
    
    0 讨论(0)
  • 2020-11-27 18:53

    This works fine for me.

     date(SUBDATE("Added Time", INTERVAL (day("Added Time") -1) day))
    

    ** replace "Added Time" with column name

    Use Cases:

    1. If you want to reset all date fields except Month and Year.

    2. If you want to retain the column format as "date". (not as "text" or "number")

    0 讨论(0)
  • 2020-11-27 18:56

    You can use the LAST_DAY function provided by MySQL to retrieve the last day of any month, that's easy:

    SELECT LAST_DAY('2010-06-15');
    

    Will return:

    2010-06-30
    

    Unfortunately, MySQL does not provide any FIRST_DAY function to retrieve the first day of a month (not sure why). But given the last day, you can add a day and subtract a month to get the first day. Thus you can define a custom function:

    DELIMITER ;;
    CREATE FUNCTION FIRST_DAY(day DATE)
    RETURNS DATE DETERMINISTIC
    BEGIN
      RETURN ADDDATE(LAST_DAY(SUBDATE(day, INTERVAL 1 MONTH)), 1);
    END;;
    DELIMITER ;
    

    That way:

    SELECT FIRST_DAY('2010-06-15');
    

    Will return:

    2010-06-01
    
    0 讨论(0)
提交回复
热议问题