Let, there is the main_table
in your database with some data. For example:
CREATE TABLE `main_table` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Date` date NOT NULL,
`Description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT main_table
(`Date`, Description)
VALUES
('2017-01-02','The first record'),
('2017-01-05','The second record'),
('2017-01-11','The third record'),
('2017-01-17','The fourth record');
Create a user defined function, that returns date of specific day of same week as specified date. Use CREATE FUNCTION syntax:
DELIMITER $$
CREATE FUNCTION `GET_DAY_OF_WEEK` (`date` DATE, `day` TINYINT UNSIGNED)
RETURNS DATE
BEGIN
RETURN `date`- INTERVAL WEEKDAY(`date`) + 1 DAY + INTERVAL `day` DAY;
END$$
DELIMITER ;
If your week is started by Monday, then use 1
for Monday and 7
for Sunday. If your week is started by Sunday, then use 0
for Sunday and 6
for Saturday. For example, my week is started by Monday, and I want to get last Wednesday date, then
SELECT GET_DAY_OF_WEEK('2017-06-03', 3);
returns '2017-05-31'
.
Thus to get records of main_table
on weekly, you could use the following MySQL query:
SELECT
ID,
WEEKOFYEAR(`Date`) AS WeekNum,
GET_DAY_OF_WEEK(`Date`, 1) AS WeekStarted,
GET_DAY_OF_WEEK(`Date`, 7) AS WeekFinished,
Description
FROM main_table;
The query result will be
ID WeekNum WeekStarted WeekFinished Description
1 1 2017-01-02 2017-01-08 'The first record'
2 1 2017-01-02 2017-01-08 'The second record'
3 2 2017-01-09 2017-01-15 'The third record'
4 3 2017-01-16 2017-01-22 'The fourth record'