计算日期范围内的平均值

时间:2014-05-15 20:07:08

标签: sql teradata

我想知道有多少人参加了任何活动(EvntFct表中的记录数量)。

这为我提供了一天的计数 - 4月1日。我使用Teradata作为我的SQl服务器。

但是,从那时起到昨天,我如何计算每日平均值?

SELECT CAST(EVENT_TIMESTAMP AS DATE) theDate,
                 COUNT(DISTINCT USER_ID) 
FROM EventFct
WHERE CAST(EVENT_TIMESTAMP AS DATE) >'2014-05-10'
GROUP BY theDate
ORDER BY theDate

2 个答案:

答案 0 :(得分:3)

好像你想要计算平均值,这是一个嵌套聚合。要实现这一点,您必须使用派生表:

SELECT avg(cnt) 
FROM
 (
   SELECT CAST(EVENT_TIMESTAMP AS DATE) theDate,
          COUNT(DISTINCT USER_ID) as cnt
   FROM EventFct
   WHERE CAST(EVENT_TIMESTAMP AS DATE) >'2014-05-10'
   GROUP BY theDate
 ) as dt

当然这会消除每个日期的行,您可能希望保留这些行并使用窗口化聚合函数将平均值添加为附加列:

SELECT CAST(EVENT_TIMESTAMP AS DATE) theDate,
       COUNT(DISTINCT USER_ID) as cnt,
       AVG(cnt) OVER () as avgcnt  
FROM EventFct
WHERE CAST(EVENT_TIMESTAMP AS DATE) >'2014-05-10'
GROUP BY theDate

答案 1 :(得分:1)

SELECT AVG(COUNT(*))
FROM EventFct
WHERE CAST(EVENT_TIMESTAMP AS DATE) > '2014-05-10'
GROUP BY USER_ID, CAST(EVENT_TIMESTAMP AS DATE)