我使用以下代码:
$sql = "SELECT SUM(Ener) AS enTot
FROM (
SELECT MAX(Ener) as en, WEEKDAY(DateTime) as day
FROM $dailyTable
WHERE WEEK(DATE(DateTime)) = WEEK(DATE('$today'), 1)
AND WEEKDAY(DATE(DateTime)) >= 0
AND WEEKDAY(DATE(DateTime)) <= 6
GROUP BY day
) AS subquery;";
按预期工作,但最终结果是从星期日到星期六的天数最大值的总和。相反,我想从星期一到星期天。
我认为使用WEEK
进行分组有问题,因为年底的一周不完整。我宁愿使用上星期一之前(包括)今天作为分组参数。
上周一可由给定的DateTime
值用以下表达式计算得出:
CAST(DATEADD(day, -((DATEPART(weekday, DateTime) + @@DATEFIRST - 2) % 7), DateTime) AS DATE) AS LastMonday
完整的查询如下所示:
SELECT SUM(Ener) AS enTot
FROM (
SELECT MAX(Ener) as en, WEEKDAY(DATEADD(day, -1, DateTime)) as day
FROM $dailyTable
WHERE CAST(DATEADD(day, -((DATEPART(weekday, DateTime) + @@DATEFIRST - 2) % 7), DateTime) AS DATE) =
CAST(DATEADD(day, -((DATEPART(weekday, GETDATE()) + @@DATEFIRST - 2) % 7), GETDATE()) AS DATE)
GROUP BY day
) AS subquery;
我的第一个想法是用DATEADD(day, -1, DateTime)
代替DateTime
和DATEADD(day, -1, '$today')
代替'$today'
to "星期天到星期六,使它属于前一周。那么工作日的条件就显得多余了。但这可能会有上述不完整周的问题。
这个计算也取决于SET DATEFIRST 1选项。