MySQL裡求給定的時間是所在月份的第幾個禮拜 Share 一個昨天寫的函數。 目的是求給定的時間是所在月份的第幾個禮拜。 [sql] DELIMITER $$ USE `t_girl`$$ DROP FUNCTION IF EXISTS `weekofmonth`$$ CREATE DEFINER=`root`@`localhost` FUNCTION `weekofmonth`( f_datetime DATETIME ) RETURNS INT(11) BEGIN -- Created by ytt. DECLARE v_result INT; DECLARE v_weekno INT; SET v_weekno = CASE DAYOFWEEK(f_datetime) WHEN 1 THEN 7 WHEN 2 THEN 1 WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 4 WHEN 6 THEN 5 WHEN 7 THEN 6 END; SET v_result = CEIL(DAYOFMONTH(DATE_SUB(f_datetime,INTERVAL v_weekno DAY))/7)+1; RETURN v_result; END$$ DELIMITER ; 演示下結果: SELECT weekofmonth(NOW()) AS result; query result: result 4