如何按周范围计算(最近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
答案 0 :(得分: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
答案 1 :(得分: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