如何从另一个没有重复的表中选择?

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

我有这样的疑问:

SELECT activity.login_time, sum(activity.sessions) FROM activity 
inner JOIN payments ON payments.user_id = activity.user_id
WHERE activity.login_time BETWEEN '2018-04-05' and '2018-04-18' 
GROUP BY activity.login_time;

我有两个表(列:activity(user\u id,sessions,login\u time)和payments(列:user\u id)。第二个有重复的值。需要从“付款”中为用户id选择会话而不重复。
我的变种不能避免重复。我应该在查询中修复什么?
谢谢!

activity
user_id login_time  sessions
101 2018-04-11  4
102 2018-04-02  1
103 2018-04-15  3
104 2018-04-06  2
104 2018-04-05  6
105 2018-04-16  1
105 2018-04-04  6
105 2018-04-01  14
106 2018-04-19  5
106 2018-04-17  3
106 2018-04-16  3
106 2018-04-15  4
106 2018-04-13  2

付款

user_id
101
103
104
106

输出

login_time  sessions
2018-04-05  ?
2018-04-06  ?
2018-04-07  ?
2018-04-08  ?
2018-04-09  ?
2018-04-10  ?
2018-04-11  ?
2018-04-12  ?
2018-04-13  ?
2018-04-14  ?
2018-04-15  ?
2018-04-16  ?
2018-04-17  ?
2018-04-18  ?
acruukt9

acruukt91#

在我看来,从你的描述你想要用户聚合

SELECT 
        a.user_id,
        SUM(a.sessions) as user_session
    FROM 
        activity a
    INNER JOIN 
        payments p ON p.user_id = a.user_id
    WHERE 
        a.login_time BETWEEN '2018-04-05' AND '2018-04-18' 
    GROUP BY 
        a.user_id;

但是,如果您想要每个用户的登录日期总和,那么使用子查询

SELECT
    a1.login_time, t1.user_session  
FROM
    activity a1 
INNER JOIN
    (SELECT 
         a.user_id,
         AVG(a.sessions) AS user_session
     FROM 
         activity a
     INNER JOIN 
         payments p ON p.user_id = a.user_id
     WHERE 
         a.login_time BETWEEN '2018-04-05' AND '2018-04-18' 
     GROUP BY 
         a.user_id) AS t1 ON a1.user_id = t1.user_id

相关问题