到目前为止我尝试过的查询
select sum(g1.datacount) from
(select DAte(DATE) as 'newdate', COUNT(RIDE_ID) as 'datacount' from
ride_Data
where date(date) between (now() - interval 90 day) and now()
group by date(date)
order by date(date) desc) as g1
where g1.newdate between (now() - interval 7 day) and now()
上述查询的简短版本,仅供说明。
select sum(g1.datacount) from g1
where g1.newdate between (now() - interval 7 day) and now()
我想实现的目标 我想对列datacount上的最后7天求和,因为您可以看到我现在已经正确完成了这部分操作,但是在实际情况下,我希望对7天对中的最后90天求和 我不知道如何将其分组?
有什么我可以将我的最后7条记录结果分组的
答案 0 :(得分:1)
如果要与现在进行比较,则可以使用DATEDIFF和DIV 7进行分组。
SELECT ((DATEDIFF(t.newdate, NOW())) DIV 7) AS WeekDiff,
-- MIN(t.newdate) AS MinDate,
-- MAX(t.newdate) AS MaxDate,
COUNT(t.RIDE_ID) as TotalRides
FROM ride_Data t
WHERE t.newdate BETWEEN (NOW() - interval 90 day) AND NOW()
GROUP BY WeekDiff
ORDER BY WeekDiff DESC;
或者只是在week上分组。
SELECT YEAR(t.newdate)*100+WEEK(t.newdate, 3) AS WeekNr,
COUNT(t.RIDE_ID) as TotalRides
FROM ride_Data t
WHERE t.newdate BETWEEN (NOW() - interval 90 day) AND NOW()
GROUP BY WeekNr
ORDER BY WeekNr DESC;