Get the values for last 6 months in mysql

前端 未结 4 1062
梦谈多话
梦谈多话 2021-01-14 10:33

I need to get last six month values from the database. Here is my Fiddle. I need to get the values dynamically. Now February. So I need August to Januar

相关标签:
4条回答
  • 2021-01-14 10:56

    For MYSQL: you may use date_add:

     SELECT * FROM ratepersqft 
    WHERE date < Now() and date > DATE_ADD(Now(), INTERVAL- 6 MONTH);
    

    For SQL Server:, dateadd :

      SELECT * FROM ratepersqft 
     WHERE date < Now() and date > DATEADD(Month, -6, Now());
    

    http://www.sqlfiddle.com/#!2/1f8029/48

    **Please wrap your date column name with backticks given it is a reserved key word. **

    MYSQL update:

    SQLFIDDLE DEMO

    SELECT *
    FROM ratepersqft 
    WHERE date_format(date,'%Y-%m') < 
                         date_format(now(),'%Y-%m')
    and date_format(date,'%Y-%m') >= 
                         date_format(now() - interval 6 month,'%Y-%m')
    order by date desc;
    
    0 讨论(0)
  • 2021-01-14 11:06

    SQLFiddle

    If you want full months only

    SELECT *
    FROM ratepersqft
    WHERE date between date_format(DATE_SUB(CURDATE(), INTERVAL 6 MONTH), '%Y-%m-01')
               and  date_sub(date_format(CURDATE(), '%Y-%m-01'), interval 1 day);
    
    0 讨论(0)
  • 2021-01-14 11:06
     SELECT
    YEAR(DATE) AS YEAR,
    SUM(MONTH(DATE) = 1) AS JAN ,
    SUM(MONTH(DATE) = 2) AS FEB ,
    SUM(MONTH(DATE) = 3) AS MAR ,
    SUM(MONTH(DATE) = 4) AS APR,
    SUM(MONTH(DATE) = 5) AS MAY ,
    SUM(MONTH(DATE) = 6) AS JUNE ,
    SUM(MONTH(DATE) = 7) AS JULY ,
    SUM(MONTH(DATE) = 8) AS AUG,
    SUM(MONTH(DATE) = 9) AS SEP ,
    SUM(MONTH(DATE) = 10) AS OCTOBER ,
    SUM(MONTH(DATE) = 11) AS NOV ,
    SUM(MONTH(DATE) = 12) AS DECE
    FROM ratepersqft
    WHERE  DATE >= NOW() - INTERVAL 6 MONTH 
    GROUP BY 1;
    
    0 讨论(0)
  • 2021-01-14 11:18

    This will consider all dates to be rounded to the beginning of the month for comparisons, and will get last 6 months from today's date:

    SELECT *
    FROM ratepersqft
    WHERE date >= DATE_SUB(DATE_FORMAT(CURDATE(), '%Y-%m-01'), INTERVAL 6 MONTH)
      AND date <  DATE_FORMAT(CURDATE(), '%Y-%m-01')
    

    Obligatory SQLFiddle.

    0 讨论(0)
提交回复
热议问题