0

我需要整个月的每日平均值,但诀窍是所有客户都有不同的开始和结束日期。例如,一些客户只注册了一个月的部分时间。假设客户 A 从 4/3/13-4/8/13 注册,客户 B 从 4/6-4/30 注册,客户 C 从 4/1-5/1 等。我该如何实现?这是我当前的代码,它返回超低计数,因为它假设所有客户都在整个月注册:

if exists (
    select  * from tempdb.dbo.sysobjects o    where o.xtype in ('U')  and o.id = object_id(N'tempdb..#enrollments_PreviousMonth2')
) DROP TABLE #enrollments_PreviousMonth2;

Select
    people_id,
    program_modifier,
    program_modifier_id,
    DATEADD(dd, 0, DATEDIFF(dd, 0, actual_date)) as enroll_midnight_date,
    actual_date as enroll_start_date,
    end_date as enroll_end_date

INTO #enrollments_PreviousMonth2 
From
 program_modifier_enrollment_view pmev with(nolock) 
Where
program_modifier_id = 'E1AA7A36-0500-4BAE-A0AA-D9E0BC91A6F3' and
actual_date  <= '4/30/13' and (end_date >= '4/1/13' or end_date is null)

;with cte as (
select cast(enroll_start_date as date) as actual_date,
    count(people_id) cnt
From #enrollments_PreviousMonth2 en
left join Calendar c on en.enroll_midnight_date = c.dt
where program_modifier_id = 'E1AA7A36-0500-4BAE-A0AA-D9E0BC91A6F3' 
    AND enroll_start_date  <= '4/30/13' and (enroll_end_date >= '4/1/13' or enroll_end_date is null)
Group by enroll_start_date--, enroll_end_date, program_modifier_id, program_modifier
)
select  
sum(cnt*1.0)
from cte

但是,我更喜欢不使用 CURSOR 作为解决方案。

4

0 回答 0