简体   繁体   English

计算日期范围内的平均值

[英]Calculate average over a date range

I'd like to find out how many people did any event (Count of records in EvntFct table). 我想找出多少人做过任何事件(EvntFct表中的记录数)。

This provides me with the count for a day - April 1st. 这为我提供了一天的时间-4月1日。 I'm using Teradata as my SQl server. 我正在使用Teradata作为我的SQl服务器。

But how would I calculate a daily average since then till yesterday? 但是从那以后直到昨天,我将如何计算每日平均值?

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

Seems like you want to calculate an average of the counts, this is an nested aggregate. 好像您要计算计数的平均值,这是一个嵌套的聚合。 To achieve this you have to use a Derived Table: 为此,您必须使用派生表:

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

Of course this eliminates the rows for each date, you might want to keep those rows and add the average as an additional column using a Windowed Aggregate Function: 当然,这消除了每个日期的行,您可能希望保留这些行,并使用Windowed Aggregate Function将平均值添加为其他列:

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
SELECT AVG(COUNT(*))
FROM EventFct
WHERE CAST(EVENT_TIMESTAMP AS DATE) > '2014-05-10'
GROUP BY USER_ID, CAST(EVENT_TIMESTAMP AS DATE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM