MySQL组本季度为7天

时间:2016-12-07 07:57:10

标签: mysql

请告知如何在不使用嵌套查询的情况下,在当前季度的7天内进行分组。 应该是这样的:

Week_period Date                      Clicks

1           1-10-2016 To 07-10-2016   30
2           8-10-2016 To 14-10-2016   40
3           15-10-2016 To 28-10-2016   20
4           29-10-2016 To 04-11-2016   10
5           05-11-2016 To 11-11-2016   80
6           12-11-2016 To 18-11-2016   90

并将持续到2016年12月31日

CREATE TABLE IF NOT EXISTS `user_click` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` datetime NOT NULL
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

感谢您的帮助..我修改了下面列出的代码:

SELECT STR_TO_DATE(CONCAT(YEARWEEK(`date`), ' Sunday'), '%X%V %W')   week_start, 
       STR_TO_DATE(CONCAT(YEARWEEK(`date`), ' Saturday'), '%X%V %W') week_end, 
       SUM(id) clicks 
FROM   `user_click`  where QUARTER(`date`) = QUARTER(CURRENT_DATE())
GROUP  BY YEARWEEK(`date`) 

但它也提供了从9月开始的日期,这是不对的。目前我的输出为:

 week_start     week_end    clicks  
2016-09-25  2016-10-01  1
2016-10-02  2016-10-08  70

但是所需的结果不匹配,因为我希望结果取决于如前所述的日期,即10月1日至10月7日。关于这方面请帮忙

3 个答案:

答案 0 :(得分:0)

我会尝试按YEARWEEK(日期)进行分组,如下所示:

  SELECT YEARWEEK("date"), count("id")
    FROM "user_click"
GROUP BY YEARWEEK("date");

您可能需要对输出进行一些操作,但这应该可以解决问题。

答案 1 :(得分:0)

您可以使用YEARWEEK对7天进行分组,此外,您可以使用STR_TO_DATE来获取本周的开始和结束时间。您可能还需要将点击总和

SELECT STR_TO_DATE(CONCAT(YEARWEEK(`date`), ' Sunday'), '%X%V %W')   week_start, 
       STR_TO_DATE(CONCAT(YEARWEEK(`date`), ' Saturday'), '%X%V %W') week_end, 
       SUM(clicks) clicks 
FROM   `user_click` 
WHERE  `date` BETWEEN '2016-10-01' AND '2016-12-31' 
GROUP  BY YEARWEEK(`date`) 

答案 2 :(得分:-1)

我使用以下查询解决了相同的问题。谢谢你的时间。

SELECT 1 + DATEDIFF(date, MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER - INTERVAL    1 QUARTER) DIV 7  AS weekNumber, MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER - INTERVAL    1 QUARTER + INTERVAL (DATEDIFF(date, MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER - INTERVAL    1 QUARTER) DIV 7) WEEK AS week_start_date, count(id)
    FROM 
        user_click 
    WHERE 
        QUARTER(date) = QUARTER(CURRENT_DATE()) AND date >= (MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER - INTERVAL 1 QUARTER)
    GROUP BY
        DATEDIFF(date, MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER - INTERVAL 1 QUARTER) DIV 7 ;