如何加入多个表并计算?

时间:2018-04-04 14:11:14

标签: sql

我有一张桌子(国家,用户,user_subscribed_disciplines,纪律,user_subscribed_study_levels,study_level)

table country
country_id | user_id | country_name

table user_subscribed_disciplines
id | user_id | discipline_id

discipline
id | name

user_subscribed_study_levels
id | user_id | study_level_id

study_level
id | name

我想得到这样的表

country | total users count | active users count | inactive users count | discipline subscribers count | top discipline | study level subscribers count | top study level

1 个答案:

答案 0 :(得分:0)

这应该让你开始:

select country_name, count(distinct a.user_id), max(name)   from 
user_subscribed_disciplines a join 
discipline b on a.discipline_id=b.discipline_id
join user_subscribed_study_levels c on a.user_id=c.user_id 
join study_level d on c.study_level_id=d.id
join country e on a.user_id=e.user_id
group by country_name