mysql - 如何定义top-3评级?

标签 mysql sql database join select

我有 3 个表:

users 
id  device
11  SM-G955F
12  iPhone8,2
13  SM-G955F
14  LG-H812
15  SM-G955F
16  SM-G955F
17  iPhone8,2

2.

activity
user_id login_time
11  2018-05-11
12  2018-05-11
13  2018-05-11
14  2018-05-12
14  2018-05-14
15  2018-05-14
11  2018-05-14
12  2018-05-14

3

payments

user_id
15
17
11

我应该做什么查询才能根据事件中的用户数量在 14.05.2018 上对设备进行前 3 评级?

需要三列:

device      number_of_users         number_of_users 
            (from activity)         (from payments if there were)

这是我的查询:

select u.device, count(distinct u.id) as number_of_users from users u inner 
join activity a on a.user_id = u.id where a.login_time = '2018-04-18' group 
by u.device order by number_of_users DESC limit 3;

但是我无法显示来自付款的用户

最佳答案

我认为您只需要另一个joincount(distinct):

select u.device, count(distinct u.id) as number_of_users,
       count(distinct p.user_id) as number_of_payment_users
from users u inner join
     activity a
     on a.user_id = u.id left join
     payments p
     on p.user_id = u.id
where a.login_time = '2018-04-18'
group by u.device
order by number_of_users desc
limit 3;

关于mysql - 如何定义top-3评级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52154796/

相关文章:

mysql - ServiceStack.OrmLite : Inserting or updating columns that are not represented in the POCO?

mysql - 对主键列使用 mediumint 而不是 int 的好处?

mysql - 缺少右括号

sql - 设置日期是从 getdate() 的一年开始吗?

mysql - Ruby on Rails - rake 数据库 :migrate is not working

c# - 如何从查询导入组合框中剪切字符串

mysql - 当JOIN表为空时如何显示数据库中的数据?

mysql - 从 TIMESTAMP 获取图表数据

mongodb - Mgo(mongo for go)支持物化路径?

mysql - 如何在 MySQL Workbench 6.0 中创建新数据库?