用Mysql语句实现报表,写一个函数,给定三个参数,年份,月份,该月份的第几周,计算出该周的起止日期。如果该月1号不在周一,则从1号所在周几到本周周日结束。如果该月最后一天不在周日,则显示最后一天对应的周几
时间: 2024-05-14 08:14:12 浏览: 65
Mysql 取字段值逗号第一个数据的查询语句
。函数实现如下:
```
DELIMITER //
CREATE FUNCTION get_week_range(year INT, month INT, week INT)
RETURNS VARCHAR(100)
BEGIN
DECLARE start_date DATE;
DECLARE end_date DATE;
DECLARE first_day_of_month DATE;
DECLARE last_day_of_month DATE;
DECLARE first_weekday INT;
DECLARE last_weekday INT;
SET first_day_of_month = CONCAT(year, '-', month, '-01');
SET last_day_of_month = LAST_DAY(first_day_of_month);
SET first_weekday = DAYOFWEEK(first_day_of_month);
SET last_weekday = DAYOFWEEK(last_day_of_month);
IF first_weekday > 2 THEN
SET start_date = DATE_SUB(first_day_of_month, INTERVAL first_weekday-2 DAY);
ELSE
SET start_date = first_day_of_month;
END IF;
IF last_weekday < 7 THEN
SET end_date = DATE_ADD(last_day_of_month, INTERVAL 7-last_weekday DAY);
ELSE
SET end_date = last_day_of_month;
END IF;
RETURN CONCAT(start_date, ' ~ ', end_date);
END //
DELIMITER ;
```
函数的参数为年份、月份和该月份的第几周,返回值为该周的起止日期(格式为'YYYY-MM-DD ~ YYYY-MM-DD')。
使用示例:
```
SELECT get_week_range(2022, 2, 3); -- 返回'2022-01-17 ~ 2022-01-23'
SELECT get_week_range(2022, 2, 4); -- 返回'2022-01-24 ~ 2022-01-31'
SELECT get_week_range(2022, 12, 1); -- 返回'2022-11-28 ~ 2022-12-04'
SELECT get_week_range(2022, 12, 5); -- 返回'2022-12-26 ~ 2022-12-31'
```
阅读全文