如何计算某个日期的平均结果?

bfrts1fy  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(372)

你能帮我吗?我有两张table。
第一个表(活动)中有:用户id、会话和登录时间。
在第二列(付款)中只有一个列-用户id。
这是我的问题:

SELECT activity.login_time, activity.user_id, avg(activity.sessions) as 
user_sessions
FROM activity
inner JOIN payments ON payments.user_id = activity.user_id
WHERE activity.login_time ='2018-04-05' group by activity.user_id;

使用此查询,我得到这样的表:

+------------+---------+---------------
| login_time | user_id | user_sessions
+------------+---------+---------------
| 2018-04-05 |     107 |       12.0000
| 2018-04-05 |     110 |        1.0000
| 2018-04-05 |     112 |        5.0000
| 2018-04-05 |     115 |        5.0000
| 2018-04-05 |     117 |        7.0000
| 2018-04-05 |     120 |        1.0000
| 2018-04-05 |     123 |        1.0000
...

如何进行查询以获得平均值:

+------------+------------
| login_time | avg_user_sessions 
+------------+---------
| 2018-04-05 | 4,57

注意:困难在于用户id重复
table

user_id login_time  sessions
107 2018-04-05  12
110 2018-04-05  1
112 2018-04-05  5
115 2018-04-05  5
117 2018-04-05  7
120 2018-04-05  1
123 2018-04-05  1

user_id
107
107
107
110
112
115
115
117
120
123
jm81lzqq

jm81lzqq1#

如果有很多 user_id 在中复制 payments table,你可以试着用 DISTINCT 在你的 user_idpayments table。
但在你的情况下,你只能选择 activity 直接,不需要 joinpayments ,因为你没有从中得到任何专栏。

CREATE TABLE activity(
   login_time date,
   user_id int,
   sessions float
);

CREATE TABLE payments (
   user_id INT
);

INSERT INTO payments VALUES (107);
INSERT INTO payments VALUES (107);
INSERT INTO payments VALUES (110);
INSERT INTO payments VALUES (112);
INSERT INTO payments VALUES (115);
INSERT INTO payments VALUES (115);
INSERT INTO payments VALUES (117);
INSERT INTO payments VALUES (120);
INSERT INTO payments VALUES (123);

INSERT INTO activity VALUES ('2018-04-05',107,12);
INSERT INTO activity VALUES ('2018-04-05',110,1);
INSERT INTO activity VALUES ('2018-04-05',112,5);
INSERT INTO activity VALUES ('2018-04-05',115,5);
INSERT INTO activity VALUES ('2018-04-05',117,7);
INSERT INTO activity VALUES ('2018-04-05',120,1);
INSERT INTO activity VALUES ('2018-04-05',123,1);

查询1:

SELECT a.login_time, avg(a.sessions) as 
user_sessions
FROM activity a
inner JOIN (SELECT DISTINCT user_id FROM payments) p ON p.user_id = a.user_id
WHERE a.login_time ='2018-04-05' 
group by a.login_time

结果:

| login_time |     user_sessions |
|------------|-------------------|
| 2018-04-05 | 4.571428571428571 |

相关问题