gpt4 book ai didi

mysql - 如何计算特定日期的平均结果?

转载 作者:行者123 更新时间:2023-11-29 05:53:19 25 4
gpt4 key购买 nike

你能帮帮我吗?我有两张 table 。
在第一个表(事件)中有:user_id、session 和 login_time。
在第二个(付款)中只有一列 - user_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

注意:困难在于user_id有重复

表格

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

最佳答案

如果 payments 表中有很多 user_id 重复,你可以尝试在你的 user_id 中使用 DISTINCT来自 payments 表。

但在你的情况下,你只能直接选择activity,不需要join with payments,因为你没有从中获取任何列。

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

Results :

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

关于mysql - 如何计算特定日期的平均结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52140831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com