我想从2015年1月1日到2016年1月1日,按月从我们的数据库中获得每月的队列分析。它需要按月按位置显示。以下是我到目前为止的情况:
Select playsite_id, count([member_guid]) members,sum(TotalVisits) visitdiff
FROM
(SELECT playsite_id, member_guid,
sum(case when [date_id] < 20150401
then 1
else null
end) as PreviousVisits,
sum(case when [date_id] between 20150401 and 20150501
then 1
else null
end) as CohortVisits,
sum(case when [date_id] between 20150401 and 20160401
then 1
else null
end) as TotalVisits w
FROM [Guest_Visit_Fact]
where visit_type in ('WALK-IN NEW','WALK-IN REPEAT')
group by playsite_id, [member_guid]) as innertable
where PreviousVisits is null and CohortVisits > 0
group by playsite_id
此代码仅适用于4月份。我们想知道是否有办法这样做,所以我们不必重写代码12次,每个月一次。也许我们过度思考它,我们已经碰壁了。这是代码返回的内容。 因此,它显示了2015年4月至2016年4月期间,首次访问的访问者数量,以及返回的访问者数量。 任何帮助,将不胜感激。我们已经很接近了。
答案 0 :(得分:0)
尝试此查询
DECLARE @MonthStart INT, @YearStart INT ,@YearEnd INT
SET @MonthStart=4
SET @YearStart=2015
SET @YearEnd=2016
WHILE @MonthStart <= 12 -- condition of months
BEGIN
Select playsite_id, count([member_guid]) members,sum(TotalVisits) visitdiff
FROM
(SELECT playsite_id, member_guid,
sum(case when MONTH([date_id]) <@MonthStart AND YEAR([date_id])=@YearStart
then 1
else null
end) as PreviousVisits,
sum(case when MONTH([date_id]) between @MonthStart and @MonthStart+1 and YEAR([date_id])= @YearStart
then 1
else null
end) as CohortVisits,
sum(case when YEAR([date_id]) between @YearStart and @YearEnd AND MONTH([date_id]) = @MonthStart
then 1
else null
end) as TotalVisits W
FROM [Guest_Visit_Fact]
where visit_type in ('WALK-IN NEW','WALK-IN REPEAT')
group by playsite_id, [member_guid]) as innertable
where PreviousVisits is null and CohortVisits > 0
group by playsite_id
SET @MonthStart=@MonthStart+1
END
GO
我希望你工作