0

如何按周范围分组计数(最近 4 周记录和周范围)?

周范围意味着 22-28、15-21、8-14、1-7

我试过这个

SELECT WEEK(PERIOD), SUM(CLICKS)
  FROM TABLE
 WHERE PERIOD >= NOW() - INTERVAL 4 WEEK
 GROUP BY WEEK(PERIOD)

SELECT WEEKOFYEAR(`date`) AS period,
       SUM(clicks) AS clicks
  FROM `tablename`
 WHERE `date` >= CURDATE() - INTERVAL 4 WEEK
 GROUP BY period
4

2 回答 2

0

如果您的意思是在今天之前的每 7 x 24 天恰好过去 4 周,直到第二天,那么

SELECT CASE WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
                    AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'
               WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
                    AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'
               WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
                    AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '8-14 days ago'
               WHEN PERIOD >= NOW() - INTERVAL 1 WEEK
                    THEN 'up to 7 days ago'
               END WeekPeriod, IFNULL(SUM(CLICKS),0) TotalClicks
  FROM TABLE
 WHERE PERIOD >= NOW() - INTERVAL 4 WEEK
 GROUP BY CASE WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
                    AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'
               WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
                    AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'
               WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
                    AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '08-14 days ago'
               WHEN PERIOD >= NOW() - INTERVAL 1 WEEK
                    THEN '01 to 7 days ago'
               END
 ORDER BY WeekPeriod
于 2012-10-28T19:22:20.260 回答
0
declare @myTable table 
(
    id bigint identity(1,1) not null primary key clustered 
    , createdDate date not null
    , clicks int not null
)

insert @myTable
      select GETUTCDATE() - 00, 9
union select GETUTCDATE() - 01, 6
union select GETUTCDATE() - 02, 5
union select GETUTCDATE() - 03, 9
union select GETUTCDATE() - 04, 3
union select GETUTCDATE() - 05, 6
union select GETUTCDATE() - 06, 3
union select GETUTCDATE() - 07, 6
union select GETUTCDATE() - 08, 9
union select GETUTCDATE() - 09, 9
union select GETUTCDATE() - 10, 8
union select GETUTCDATE() - 11, 7
union select GETUTCDATE() - 12, 1
union select GETUTCDATE() - 13, 2
union select GETUTCDATE() - 14, 5
union select GETUTCDATE() - 15, 3
union select GETUTCDATE() - 16, 8
union select GETUTCDATE() - 17, 7
union select GETUTCDATE() - 18, 4

select DATEPART(week, createdDate) Period
, SUM(clicks) ClickSum
from @myTable
group by DATEPART(week, createdDate)
order by Period 
于 2012-10-28T19:02:02.420 回答