假设我有2011年1月3日,我想在一周的第一天,也就是星期天,那是2011年1月2日,我该怎么做?

原因是我有此查询:

select
  YEAR(date_entered) as year,
  date(date_entered) as week,   <-------This is what I want to change to select the first day of the week.
  SUM(1) as total_ncrs,
  SUM(case when orgin = picked_up_at then 1 else 0 end) as ncrs_caught_at_station
from sugarcrm2.ncr_ncr
where
sugarcrm2.ncr_ncr.date_entered > date('2011-01-01')
and orgin in(
'Silkscreen',
'Brake',
'Assembly',
'Welding',
'Machining',
'2000W Laser',
'Paint Booth 1',
'Paint Prep',
'Packaging',
'PEM',
'Deburr',
'Laser ',
'Paint Booth 2',
'Toolpath'
)
and date_entered is not null
and orgin is not null
AND(grading = 'Minor' or grading = 'Major')
 and week(date_entered) > week(current_timestamp) -20
group by year, week(date_entered)
order by year   asc, week asc

是的,我意识到起源拼写错误,但是在此之前我就在这里,因此由于太多内部应用程序引用了它,因此我无法对其进行更正。

因此,我按周分组,但我希望以此填充我的图表,所以我不能让所有的周初看起来都像不同的日期。我该如何解决?

最佳答案

如果您需要处理从星期一开始的几周,也可以这样做。首先定义一个自定义FIRST_DAY_OF_WEEK函数:

DELIMITER ;;
CREATE FUNCTION FIRST_DAY_OF_WEEK(day DATE)
RETURNS DATE DETERMINISTIC
BEGIN
  RETURN SUBDATE(day, WEEKDAY(day));
END;;
DELIMITER ;

然后您可以执行以下操作:
SELECT FIRST_DAY_OF_WEEK('2011-01-03');

为您提供信息,MySQL提供了两种不同的功能来检索一周的第一天。有DAYOFWEEK:



WEEKDAY:

关于mysql - 如何在mysql中获取日期的一周的第一天?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6944055/

10-11 03:51
查看更多