2

我遇到的问题是在运行此查询时,它从当前日期开始一周间隔(从当前日期减去 7 天)。我想做所有前 10 周(周日至周一)。因此,如果我当前的日期是星期一、星期二或星期三,我希望它从最近的星期日开始,然后回顾过去的 10 周。我相信我必须使用WEEKDAYDAYOFWEEKDATE_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
4

1 回答 1

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

您也可以使用 pilcrow 建议的其他方式:

SUBDATE(CURDATE(), DAYOFWEEK(CURDATE()) - 1)

哪个更具可读性...

于 2012-11-26T17:11:33.260 回答