简体   繁体   中英

How to calculate average value?

I have two tables. Into the first table (activity) there are: user_id, sessions and login_time. Into the second (payments) there's only one column - user_id.

I need to calculate how many sessions did users from "payments" do during 01/01/2018-01/05/2018.

activity

user_id   sessions   login_time
1           6         01.01.2018
2           2         01.01.2018
1           1         02.01.2018
4           3         02.01.2018
1           2         03.05.2018
3                     04.02.2018

table

payments
user_id
1
3
4

My code (calculates wrong):

select login_time, avg(activity.sessions) AS
average_sessions
from activity inner join
payments
on payments.user_id = activity.user_id
where activity.login_time between '2018-01-01' and '2018-05-01' 
group by activity.login_time;

Thanks for help!

Output:

output
login_time    average_sessions
01.01.2018     6
02.01.2018     2
03.01.2018     0
04.01.2018     0
...

looking to your sample
seems you need the sum of session divided by the number of totals days

  select  user_id, sum(sessions)/t.num_days
  from activity 
  cross join  (
  select count(distinct login_time) num_days
  from activity
  ) t 
  group by user_id  

and if you need only the user_id in payments

  select  user_id, sum(sessions)/t.num_days
  from activity 
  cross join  (
  select count(distinct login_time) num_days
  from activity
  ) t 
  inner join  payments p on p.user_id = activity.user_id
  group by user_id  

and looking to your formaed result seems you need

  select t1. login_time, ifnull(t2.avg_sess) average_sessions
  from (
  select distinct login_time 
  from activity 
  ) t1  
  left join (
  select a.login_time, avg(a.session) avg_sess
  from activity a
  inner join payments p on a.user_id  = p.user_id
  group by a.login_time
  ) t2 on t1.login_time = t2.login_time

Based on your expected output, use the following:

SELECT login_time, 
       SUM(activity.sessions)/COUNT(DISTINCT activity.user_id) AS average_sessions
FROM activity 
INNER JOIN payments ON payments.user_id = activity.user_id
WHERE activity.login_time BETWEEN '2018-01-01' and '2018-05-01' 
GROUP BY activity.login_time;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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