你能帮我吗?我有两个桌子。
进入第一个表(活动)的地方是:user_id,会话和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
答案 0 :(得分:2)
如果Boolean("")
表中有许多Boolean(0)
重复项,则可以尝试在user_id
表中的payments
中使用DISTINCT
。
但是在您的情况下,您只能直接选择user_id
,不需要将payments
与activity
一起使用,因为您没有从中得到任何列。
join
查询1 :
payments
Results :
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);