如何获得一个月的每日平均值?

时间:2013-05-10 16:54:52

标签: tsql average common-table-expression

如何返回整月的每日平均值?

select count(distinct people_id) 
from #enrollments_PreviousMonth
where program_modifier_id = 'E1AA7A36-0500-4BAE-A0AA-D9E0BC91A6F3' 
AND actual_date between '4/1/13' and '5/1/13'

以上是我当前代码的一部分。我希望在4月份的每一天都能得到明显的people_id数量。然后我想平均4月份的这些计数。例如,如果计数在4月1日为764,在4月2日为763,那么我将总计764和763 = 1527.同样,我将在4月份每天汇总。最后,我将按四月的天数除以得到我的日平均值。什么是最有效的TSQL来实现这一目标?有没有我可以用于这个或其他标准SQL运算符的CTE?

3 个答案:

答案 0 :(得分:0)

你可能想要使用这样的东西

SELECT round(Cast(count(people_id)as float) / Cast(DateDiff(day, '4/1/13', '4/6/13')as float), 2) as average
    FROM #enrollments_PreviousMonth
    WHERE program_modifier_id = 'E1AA7A36-0500-4BAE-A0AA-D9E0BC91A6F3' 
        AND actual_date between '4/1/13' and '5/1/13'
    GROUP BY people_id

答案 1 :(得分:0)

WITH list AS (
select actual_date,count(distinct people_id) cnt
from #enrollments_PreviousMonth
where program_modifier_id = 'E1AA7A36-0500-4BAE-A0AA-D9E0BC91A6F3' 
AND actual_date between '4/1/13' and '5/1/13'
GROUP  BY actual_date )
SELECT AVG(cnt) FROM list

答案 2 :(得分:0)

SELECT AVG(CONVERT(FLOAT, distinctPeopleByDate))
FROM
(
    select actual_date, count(distinct people_id) as distinctPeopleByDate
    from #enrollments_PreviousMonth
    where program_modifier_id = 'E1AA7A36-0500-4BAE-A0AA-D9E0BC91A6F3' 
    and actual_date between '4/1/13' and '5/1/13'
    group by actual_date
) x