2011-03-28 3 views
0

:슬라이딩 창 평균 - SQL 서버 I는 지난 30 일에 가입 우리의 사용자 로그온에 대한 평균 시간 반환하는 SQL 쿼리가

select avg(datediff(dd, acquisitiontime,createdate)) from users where 
createdate > getdate() - 30 and 
acquisitionmedium = 'cpc' and 
acquisitionsource = 'google' and 
acquisitiontime is not null 

내가 어떻게보고 싶어를 시간이 지남에 따라 변경되었습니다.

이 쿼리를 변경하여 (달, 평균 월간 가입 시간) 테이블을 뱉어 낼 수 있습니까?

답변

2
select 
    DATEADD(month, -n.number, getdate()) OneMonthFromThisDate, 
    avg(datediff(dd, acquisitiontime, createdate)) AverageInThisMonth 
from users 
join master..spt_values n on n.type='P' and n.number between 1 and 24 
where createdate > DATEADD(month, -n.number, getdate()) 
    and createdate <= DATEADD(month, 1-n.number, getdate()) 
    and acquisitionmedium = 'cpc' 
    and acquisitionsource = 'google' 
    and acquisitiontime is not null 
group by n.number, DATEADD(month, -n.number, getdate()) 
order by n.number 

가장 최근의 것입니다.

+0

캘린더 개월을 원한다면 숫자 시퀀스에서 약간 돌아 오는 날짜 범위를 수정하십시오. – RichardTheKiwi