用于计算缺少某些日期记录的列的每日平均值的sql

8oomwypt  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(355)

我有如下表格:

我必须计算每个用户每天会话的平均次数。
首先,我计算了每个用户每天的会话总数,并从中计算出每天会话的平均数。我知道它不会工作,因为所有用户没有会话的每个日期。一些日期是所有用户丢失。当某些日期没有条目时,有没有办法计算日均值

WITH daily_count AS
(
  SELECT user_id,  to_char(local_time,’MM/DD/YYYY’) AS Date, count(session_id) AS  total_count
  FROM table_name
  GROUP BY device_id, to_char(local_time,’MM/DD/YYYY’)
)
SELECT user_id , AVG(total_count) AS average_session_count
FROM daily_count
GROUP BY user_id 

For eg: The max date in the above given table is Feb04 and the min date is Jan31 .So the total no of days is 5 days.If we take Userid 1, it is having records only for 2 dates. So the query i wrote will calculate average for 2 days not for 5 days. How to make it to calculate average for 5 days
bksxznpy

bksxznpy1#

如果用于日期 1,2,3 一个用户的会话数为 1,0(no sessions),5 那么您希望在平均会话中获得什么输出?--> 2 or 3 ?
您需要按以下方式更改主查询:

SELECT USER_ID,
       AVG(TOTAL_COUNT) AS AVERAGE_SESSION_COUNT -- if you want output as 3 then use this
       --SUM(TOTAL_COUNT)/(MAX(DATE) - MIN(DATE) + 1) -- if you want output as 2 then use this
  FROM DAILY_COUNT
 GROUP BY USER_ID

相关问题