Sobes.tech
Junior

Analysis of fitness club attendance You work as an analyst in a chain of fitness clubs. You have information about user visits and the memberships they purchase. It is necessary to analyze the effectiveness of membership usage. Calculate for each type of membership: • the total number of users who used this type of membership. Consider only unique user_id; • the total number of visits for this membership. Consider all visits of users with this membership; • the share of users of this membership in percentage of the total number of all users (rounded to one decimal place). To calculate the share, use the ratio of the number of users with this membership to the total number of all unique users. Each user can have only one membership. Sort the result by membership type in alphabetical order. Input format Memberships table: • membership_id (int) — unique membership identifier • user_id (int) — unique user identifier • membership_type (text) — type of membership Visits table: • visit_id (int) — unique visit identifier • user_id (int) — user identifier • visit_date (timestamp) — date and time of visit Data does not contain missing or incorrect values. Output format The query should return a table with fields in this order: • membership_type (text) — type of membership • users_count (int) — number of unique users with this type of membership • total_visits (int) — total number of visits of users with this membership • user_share (numeric) — share of users of this membership in percentage of the total number (rounded to 1 decimal place) The result is sorted by membership type in alphabetical order.

sobes.tech AI

Answer from AI

sql WITH user_counts AS ( SELECT membership_type, COUNT(DISTINCT user_id) AS users_count FROM memberships GROUP BY membership_type ),

total_users AS ( SELECT COUNT(DISTINCT user_id) AS total FROM memberships ),

visits_count AS ( SELECT m.membership_type, COUNT(v.visit_id) AS total_visits FROM visits v JOIN memberships m ON v.user_id = m.user_id GROUP BY m.membership_type )

SELECT uc.membership_type, uc.users_count, COALESCE(vc.total_visits, 0) AS total_visits, ROUND((uc.users_count::numeric / t.total) * 100, 1) AS user_share FROM user_counts uc JOIN total_users t ON true LEFT JOIN visits_count vc ON uc.membership_type = vc.membership_type ORDER BY uc.membership_type;