简体   繁体   中英

MySQL GROUP BY WEEK Starting 1st of month

Need to GROUP BY WEEKS Starting from 1st of current month

DDLs:

CREATE TABLE `group_by_week` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `date` date DEFAULT NULL,
  `value` int(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `group_by_week`
(`date`,`value`)
VALUES
('2016-01-01',1),
('2016-01-02',2),
('2016-01-03',3),
('2016-01-04',4),
('2016-01-05',5),
('2016-01-06',6),
('2016-01-07',7),
('2016-01-08',8),
('2016-01-09',9),
('2016-01-10',10),
('2016-01-11',11),
('2016-01-12',12),
('2016-01-13',13),
('2016-01-14',14),
('2016-01-15',15),
('2016-01-16',16);

EXPECTED RESULT:

week 1 => 28

week 2 => 77

week 3 => 31

Eg:

SELECT CEILING(DATE_FORMAT(date,'%d')/7) w
     , SUM(value) week_total 
  FROM group_by_week 
 GROUP 
    BY w;

Obviously, you need to extend the logic a little if dealing with more than one month, but I'll leave that as an exercise for the reader.

Note also that the '4' in 'INT(4)' is fairly meaningless - I doubt very much that it does whatever you think it does.

You may need to get the week number by diving the Day part with 7 and then you may need to round the result using FLOOR .

If dates from different months are there, then its better to add month name along with the week number. So I just did that way. So the first column values would be like monthname weeknumber . And we can group by with the same first column.

Query

SELECT
  CONCAT(MONTHNAME(`date`), ' week ', FLOOR(((DAY(`date`) - 1) / 7) + 1)) `month & week`, 
  SUM(`value`) AS `value`
FROM `group_by_week`
GROUP BY `month & week`
ORDER BY month(`date`), `month & week`;

Result

+-----------------+-------+
| month & week    | value |
+-----------------+-------+
| January week 1  |  28   |
| January week 2  |  77   |
| January week 3  |  31   |
+-----------------+-------+

SQL Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM