我遇到的问题是,在运行此查询时,它会从当前日期(从当前日期起减去7天)开始一周的间隔。我想做所有前10周(周一至周日)。因此,如果我的当前日期是星期一,星期二或星期三,我希望它在最近的星期日开始,然后回顾前10周。我相信我必须在WEEKDAY
中使用DAYOFWEEK
或DATE_SUB
,但尝试无效:
SELECT
SUM(MT.QUANTITY) as qty,
WEEKDAY(MT.TRANS_DATE) AS WEEKDAY,
WEEK(MT.TRANS_DATE) AS WEEK,
YEAR(MT.TRANS_DATE) AS YEAR
FROM
mytable MT
WHERE
MT.TRANS_DATE > DATE_SUB(CURDATE(), INTERVAL 10 WEEK)
GROUP BY WEEK
答案 0 :(得分:4)
尝试使用DATE_SUB(STR_TO_DATE(CONCAT(YEAR(CURDATE()),WEEK(CURDATE()),' Sunday'), '%X%V %W'),INTERVAL 10 WEEK)
,如下所示:
SELECT
SUM(MT.QUANTITY) as qty,
WEEKDAY(MT.TRANS_DATE) AS WEEKDAY,
WEEK(MT.TRANS_DATE) AS WEEK,
YEAR(MT.TRANS_DATE) AS YEAR
FROM
mytable MT
WHERE
MT.TRANS_DATE > DATE_SUB(STR_TO_DATE(CONCAT(YEAR(CURDATE()),WEEK(CURDATE()),' Sunday'), '%X%V %W'),INTERVAL 10 WEEK)
GROUP BY WEEK
你也可以用另一种方式建议:
SUBDATE(CURDATE(), DAYOFWEEK(CURDATE()) - 1)
哪个更具可读性......