2016-12-07 98 views
-1

請告訴如何在不使用嵌套查詢的情況下按當前季度的7天進行分組。 它應該是這樣的:本季度爲7天的MySQL集團

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 

而且將持續到31-12-2016

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`) 

但它會給出一個來自九月的日期,這也是不正確的。目前,我正在輸出:

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

但我想結果取決於如前面所述的天數,即10月1日至十月七日所需要的結果不匹配。請有關這方面

+0

提供你的表結構 – Beginner

+0

@Newbee開發請看看錶結構 –

+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-爲什麼看起來對我來說是一個非常簡單的sql查詢 – Strawberry

回答

0

我會嘗試按YEARWEEK(日期),所以像這樣幫助:

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

您可能需要皮條客輸出一點點,但這個應該做的伎倆。

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`) 
+0

嘗試這裏提到的解決方案:http://stackoverflow.com/questions/14379337/group-rows-by-7-天間隔起動-從-A-某些最新 – phobia82

-1

I解決了使用以下查詢的問題。謝謝你的時間。

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 ;