想要查詢上月第2個周末的數據,我們需要用到一些 MySQL 的函數。這里我們將使用 WEEK() 和 DAYOFWEEK() 函數。
首先,我們需要獲取上一個月的年份和月份。可以使用以下查詢語句:
SELECT YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AS prev_year, MONTH(CURRENT_DATE - INTERVAL 1 MONTH) AS prev_month;
接下來,我們可以使用 WEEK() 函數來獲取上一個月的第一天和最后一天的周數。這樣我們就可以知道上一個月有多少周了。
SELECT WEEK(CONCAT(prev_year, '-', prev_month, '-01')) AS first_week, WEEK(LAST_DAY(CONCAT(prev_year, '-', prev_month, '-01'))) AS last_week;
現在我們已經知道了上一個月有多少個周了,我們就可以使用 DAYOFWEEK() 函數來獲取上一個月每一天是周幾了。這樣我們就可以篩選出第 2 個周末了。
SELECT CONCAT(prev_year, '-', prev_month, '-', DAY) AS date, DAYNAME(CONCAT(prev_year, '-', prev_month, '-', DAY)) AS week_day, WEEK(CONCAT(prev_year, '-', prev_month, '-', DAY)) AS week, @cnt := IF(week = first_week AND week_day = 'Saturday', 1, IF(week = first_week AND WEEKDAY(CONCAT(prev_year, '-', prev_month, '-01'))< 5, 1, IF(week = first_week + 1 AND WEEKDAY(CONCAT(prev_year, '-', prev_month, '-01')) >4, 1, 0))) AS cnt, @cnt := IF(week_day = 'Saturday' OR week_day = 'Sunday', @cnt + 1, @cnt) AS weekend_cnt FROM ( SELECT DAY FROM ( SELECT DAYOFMONTH(CONCAT(prev_year, '-', prev_month, '-', 1 - DAYOFWEEK(CONCAT(prev_year, '-', prev_month, '-01')) + (@num := @num + 1))) AS DAY FROM mysql.help_topic JOIN (SELECT @num:=-1) num WHERE DAY<= LAST_DAY(CONCAT(prev_year, '-', prev_month, '-01')) ) AS day_numbers ) AS days, (SELECT @cnt:=0) cnt HAVING weekend_cnt = 2 AND cnt = 1;
以上就是獲取上月第二個周末的 MySQL 查詢語句。希望對大家有所幫助!