我必须计算用于报告的aggrgated列,并将所有列放在一个表中。我创建了一个参考日期表来比较日期。
我的源表看起来像(模拟数据)
memberid startdate enddate
1 2017-05-23 2017-06-21
2 2017-05-01 2017-06-17
3 2017-04-23 2017-05-28
4 2017-06-01 2017-07-21
5 2017-04-30 2017-05-27
我必须每周进行一次计算,这将是一个累积的计算方法。例如,如果我想在2017-06-04运行报告,那么我必须计算前一周的数据。 每周应该低于指标。
1. how many members are new this week? count(Id's) where startdate >= 2017-05-28
2. how many are discharged this week? count(Id's) where enddate=2017-05-27
3. how many are still in service? count(ID's) where startdate<=2017-05-28 and enddate >= 2017-05-28
我为#1和#2创建了聚合计算但无法找到#3。 以下计算针对#1和#2进行。 --newmembers
1.select DATEADD(DAY, 1 - DATEPART(WEEKDAY, c.pkdate), CAST(c.pkdate AS DATE)) as weekdate,count(distinct memberid) as newmembers from #tempauth t
join [dbo].[Calendardays] c
on dateadd(dd,-7,dateadd(dd,-1,weekstart)) =DATEADD(DAY, 1 - DATEPART(WEEKDAY, startdate), CAST(startdate AS DATE))
group by DATEADD(DAY, 1 - DATEPART(WEEKDAY, c.pkdate), CAST(c.pkdate AS DATE))
- 排出
2.select DATEADD(DAY, 1 - DATEPART(WEEKDAY, c.pkdate), CAST(c.pkdate AS DATE)) as weekdate,count(distinct memberid) as dischargedmembers from #tempauth t
join [dbo].[Calendardays] c
on dateadd(dd,-8,dateadd(dd,-1,weekstart)) =t.enddate
group by DATEADD(DAY, 1 - DATEPART(WEEKDAY, c.pkdate), CAST(c.pkdate AS DATE))
任何人都可以帮助我找到仍在服役的成员(#3)吗?另外,我必须计算这三个计算并将单表放入我的报告中。我怎么能这样做?
答案 0 :(得分:0)
您可以计算之前的几周&#39;相关日期(例如在CTE中)并将结果作为子查询返回:
with cte as
(
select distinct
DATEADD(dd, -(DATEPART(dw, pkdate) - 1), pkdate) as FirstDayOfWeek,
DATEADD(DAY, 7 - (DATEPART(dw, pkdate)), pkdate) as LastDayOfWeek
from dbo.Calendardays
where pkdate <= dateadd(day, -8, getdate()) --> Calendardays until last week
)
select (select count(distinct memberid)
from #tempauth t
where t.StartDate >= cte.FirstDayOfWeek) as NewMembers,
(select count(distinct memberid)
from #tempauth t
where ...) as DischargedMembers
(select count(distinct memberid)
from #tempauth t
where ...) as MembersStillInService
from cte;