查询查找一年中每个月的第二个星期六

时间:2010-04-29 12:23:41

标签: mysql

我需要帮助来编写一个查询:

如何找到一年中每个月的第二个星期六?

2 个答案:

答案 0 :(得分:1)

有一种很好的技术可以证明如何做到这一点here。向下滚动到提示#23。它将让您创建一个小表以方便查询。创建表后,您的查询就像这样:

SELECT monthdate AS first_day_of_month,
    DATE_ADD(monthdate, 
        INTERVAL( ( 10 - DAYOFWEEK(monthdate) ) % 7 ) + 7 DAY) AS second_saturday_of_month
FROM monthdates

答案 1 :(得分:1)

这是orbman想法的锻炼,谢谢orbman。

首先你的桌子是这样的,

CREATE TABLE `monthdates` (
  `monthdate` date NOT NULL,
  PRIMARY KEY  (`monthdate`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

INSERT INTO `monthdates` VALUES ('2010-02-01');
INSERT INTO `monthdates` VALUES ('2010-03-01');
INSERT INTO `monthdates` VALUES ('2010-04-01');
INSERT INTO `monthdates` VALUES ('2010-05-01');
INSERT INTO `monthdates` VALUES ('2010-06-01');
INSERT INTO `monthdates` VALUES ('2010-07-01');

在此表中,您提供了第一个月的日期。

然后在第二个星期六使用此查询,

    SELECT monthdate AS first_day_of_month, DATE_ADD(monthdate, INTERVAL( ( 14 - DAYOFWEEK(monthdate) ) % 7 ) + 7 DAY) AS second_saturday_of_month, DAYNAME(DATE_ADD(monthdate, INTERVAL( ( 14 - DAYOFWEEK(monthdate) ) % 7 ) + 7 DAY)) as dayy
 FROM monthdates

输出是:

first_day_of_month  second_saturday_of_month    dayy
2010-02-01  2010-02-13  Saturday
2010-03-01  2010-03-13  Saturday
2010-04-01  2010-04-10  Saturday
2010-05-01  2010-05-08  Saturday
2010-06-01  2010-06-12  Saturday
2010-07-01  2010-07-10  Saturday