在mysql中获取最近6个月的记录

时间:2018-10-16 14:18:30

标签: mysql

我一直在进行查询以返回最近的6个月,例如:

如果当前月份为2018年4月,则查询应返回最近6个月的记录,例如:

  • 2017年11月
  • 2017年12月
  • 2018年1月
  • 2018年2月
  • 2018年3月
  • 2018年4月

我当前的查询是:

SELECT DISTINCT
  monthname(batchEndDate) AS month,
  batchDetails.bATCHiD,
  batchDetails.batchEndDate,
  COUNT(EnrollmentNumber) AS count
FROM candidate
INNER JOIN batchdetails
  ON candidate.batchId = batchDetails.batchId
WHERE (assessmentResult = "pass"
OR assessmentResult = "fail")
AND YEAR(batchEndDate) BETWEEN YEAR(batchEndDate) - 1
AND YEAR(curdate())
GROUP BY MONTH(batchEndDate)
ORDER BY month(batchEndDate);

1 个答案:

答案 0 :(得分:1)

这是MySQL非常有用的日期算法的工作。特别是LAST_DAY() function使这一点变得简单。

下个月的第一天可以通过以下方式获取:

 LAST_DAY(CURDATE()) + INTERVAL 1 DAY

因此,您需要所有在此之前的记录。...

  WHERE batchEndDate < LAST_DAY(CURDATE()) + INTERVAL 1 DAY

六个月前一个月的第一天是

 LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 6 MONTH

因此,您想要此后的所有记录。

  WHERE batchEndDate < LAST_DAY(CURDATE()) + INTERVAL 1 DAY
    AND batchEndDate >= LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 6 MONTH

您要按月分组。您可以这样做

GROUP BY LAST_DAY(batchEndDate)

然后您的查询如下所示

select LAST_DAY(batchEndDate) as month_ending,
       monthname(LAST_DAY(batchEndDate)) as month,
       count(EnrollmentNumber) as count 
  from candidate 
 inner join batchdetails on candidate.batchId = batchDetails.batchId 
 where (assessmentResult="pass" or assessmentResult="fail") 
   and batchEndDate < LAST_DAY(CURDATE()) + INTERVAL 1 DAY
   and batchEndDate >= LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 6 MONTH
 GROUP BY LAST_DAY(batchEndDate)