我有一个包含大量记录的mysql表tbl_track
User_id | User_country | Datecreated (timestamp)
1 |3 | 2012-09-09 09:37:03
2 |7 | 2012-10-09 16:22:36
现在我希望得到一个像这样的结果(从开始月份到当月)
September | September & October
1 record | 2 records
我试试这个,但结果是相反的,从当月到月初,即(十月,十月+九月,十月+九月+八月)。我也为每个
写了单独的查询我当前月的查询是
SELECT * FROM tbl_track
WHERE YEAR(`date_created`) = YEAR(CURRENT_DATE)
AND MONTH(`date_created`) = MONTH(CURRENT_DATE)
我对当前&的查询上个月是
SELECT * as count FROM tbl_track
WHERE YEAR(`date_created`) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(`date_created`) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
答案 0 :(得分:1)
据我所知,在查询中没有简单的方法可以做到这一点。但是,您可以使用以下内容:
SELECT COUNT(1), MONTH(date_created) AS mm, YEAR(date_created) AS yy
FROM tbl_track
GROUP BY mm, yy
这会为您提供每月记录数量的列表。基于你的phpmyadmin标签,我假设你要在PHP脚本中使用结果集,那么也许你可以在该脚本中对前几个月的数量进行累积计算?
答案 1 :(得分:0)
您对当前和上个月的查询只提取上个月的记录
SELECT * as count FROM tbl_track
WHERE YEAR(`date_created`) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(`date_created`) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
我认为你应该把它改成
SELECT count(*) as countofrec FROM tbl_track
WHERE YEAR(`date_created`) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND ( MONTH(`date_created`) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
OR
MONTH(`date_created`) = MONTH(CURRENT_DATE) )