我有一个像两列一样简单的表名称,日期 - 这是一个包含" Leads"当用户从我们的网站查询时。
我需要生成一个过去10周的铅计数数据集吗?
预期输出为
Starting Week -- Count
==============
10 SUM(Last 10 weeks)
9 SUM(Starting from Week 9 for Last 10 weeks)
8 SUM(Starting from Week 8 for Last 10 weeks)
依此类推..它将有10行
它喜欢滑回一周,然后从那里算起最后10周任何帮助?
答案 0 :(得分:2)
您可以像这样对计数进行累积总和:
select DATEPART(week, [Date]) AS weekNo
,sum(count(*))
over (order by DATEPART(week, [Date])
rows unbounded preceding)
from tab
where ...
group by DATEPART(week, [Date])
答案 1 :(得分:2)
完全窗口子句应该做什么。但是,您首先需要聚合数据:
select date, count(*) as cnt
from simple s
group by date;
假设您每天都有数据,那么您需要70天的计数。你可以通过总计70天的计数来得到它。那将是:
select date, count(*) as cnt,
sum(count(*)) over
(order by date rows between 69 preceding and current row)
from simple s
group by date;
这几天都有效。要在几周内完成此操作,您需要执行一些操作将天数转换为几周,然后更改窗口子句。您没有定义一周,但这可能接近您想要的一周:
select dateadd(day, 1 - datepart(weekday, date), date) as weekstart,
count(*) as cnt,
sum(count(*)) over
(order by dateadd(day, 1 - datepart(weekday, date), date) rows between 9 preceding and current row)
from simple s
group by dateadd(day, 1 - datepart(weekday, date), date)
order by weekstart;
答案 2 :(得分:0)
您可以使用以下查询:
SELECT Name,
weekSlide + 1 AS weekSlide,
COUNT(CASE WHEN weekDiff BETWEEN 0 AND 9 THEN 1 END) AS [Count]
FROM (
SELECT Name,
DATEPART(week, [Date]) AS weekNo,
(x.c - DATEPART(week, [Date])) +
(YEAR(GETDATE()) - DATEPART(year, [Date])) * 52 -
y.weekSlide AS weekDiff,
y.weekSlide
FROM mytable
CROSS JOIN (SELECT DATEPART(week, GETDATE())) x(c) -- current week number
CROSS JOIN (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) AS y(weekSlide)) t
GROUP BY Name, weekSlide
weekSlide
是周窗口的计数器,即包含从当前日期开始的最后10周的周窗口的0
,从上周开始的周窗口1
等等。
weekDiff
是一个计算列,其中包含每个weekSlide
的[日期]的偏移量。负偏移意味着超过周窗口的[日期]。
答案 3 :(得分:0)
我会用:
DECLARE @week INT, @end_date DATE
DECLARE @results AS TABLE (starting_week INT, count INT)
SET @week = 0
WHILE @week < 10
BEGIN
SELECT @end_date = DATEADD(dd, @week * (-7), GETDATE())
INSERT INTO @results
SELECT (10 - @week),
COUNT(1) FROM Leads
WHERE Date BETWEEN (DATEADD(dd, -70, @end_date)) AND @end_date
@week = @week + 1
END
SELECT * FROM @results
编辑:虽然Brian的问题(评论添加到您的初始问题中)是一个很好的问题 - 如果它不是&#34;从今天开始回滚&#34;,那么你&#39 ; d需要在@end_date
的定义中添加另一行逻辑。