Mysql:如何从去年7月到当前日期获取数据

时间:2018-04-30 07:50:03

标签: mysql sql

我知道如何获取7月的数据

SELECT * FROM tableName 
   WHERE MONTH(created) = 7

但是如何在去年7月到当前日期之间获取数据?

4 个答案:

答案 0 :(得分:1)

从您的查询中,我会选择:

SELECT * FROM tableName 
WHERE MONTH(created) = 7 
AND (
( MONTH(CURDATE()) <= 7 AND YEAR(created) = YEAR(CURDATE()) - 1 )
OR 
( MONTH(CURDATE()) > 7 AND YEAR(created) = YEAR(CURDATE()) )
)

如果你想(如你在评论中提到的那样)数据,请查看:

SELECT * FROM tableName 
    WHERE created <= CURDATE()
    AND (
    (
    MONTH(CURDATE()) <= 7
    AND created >= DATE_SUB(DATE_FORMAT(CURDATE(), '%Y-07-01'), INTERVAL 1 YEAR)
    )
    OR
    (
    MONTH(CURDATE()) > 7
    AND created >= DATE_FORMAT(CURDATE(), '%Y-07-01')
    ));

答案 1 :(得分:0)

在查询下方使用。

SELECT 
  * 
FROM
  `tableName`
WHERE MONTH(created) = 7 
AND
(CASE WHEN (MONTH(CURRENT_DATE()) < 7) 
 THEN
       YEAR(created) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
 ELSE
       YEAR(created) = YEAR(CURRENT_DATE())
 END)

答案 2 :(得分:0)

Bro现在试试......

    SELECT * FROM  Table_Name
WHERE event_date between (case when month(GETDATE()) >6
                                then cast( concat(year( GETDATE()),'-07-01')as datetime)    
                                    else cast( concat(year( GETDATE())-1,'-07-01')   as datetime) 
                                    end)  and GETDATE()

答案 3 :(得分:0)

如果你想要去年七月的 数据,那么你需要找到去年七月的日期。

select t.*
from t
where (month(now()) > 7 and t.created >= date(concat(year(now()), '-01-01')) or
      (month(now()) <= 7 and t.created >= date(concat(year(now()) - 1, '-01-01')) ;