Create a SQL interview that test a candidate's skills on slowly change dimension type 2, with settings of a netflix like app. Provide table schemas. Candidate need to design the data model, and write sql queries to answer the question
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure, here's an SQL interview question that tests a candidate's skills on slowly changing dimension type 2.
Scenario:
You are a data analyst working for a Netflix-like app. The company has provided you with two tables:
users - This table contains information about the app users, such as their name and email address.
user_subscription_history - This table contains information about the users' subscription history, such as when they subscribed and canceled.
You need to design a data model to store this information and write SQL queries to answer the following questions:
What is the current subscription status of each user?
How many users subscribed in a given month?
What was the total revenue generated in a given month?
Table Schemas:
sql
CREATE TABLE users (
user_id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE user_subscription_history (
subscription_id INT PRIMARY KEY,
user_id INT NOT NULL,
subscription_start_date DATE NOT NULL,
subscription_end_date DATE,
subscription_status VARCHAR(50) NOT NULL,
subscription_price DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
Design the Data Model:
To implement the slowly changing dimension type 2, we need to add a new column to the user_subscription_history table, which will store the start date of the current subscription. When a user's subscription status changes, a new row will be inserted into the table with the new subscription start date and the old row's end date updated.
sql
ALTER TABLE user_subscription_history ADD COLUMN current_subscription_start_date DATE;
SQL Queries:
What is the current subscription status of each user?
vbnet
SELECT u.user_id, u.name, u.email, ush.subscription_status
FROM users u
JOIN (
SELECT user_id, subscription_status
FROM user_subscription_history
WHERE current_subscription_start_date <= NOW() AND (subscription_end_date IS NULL OR subscription_end_date > NOW())
GROUP BY user_id
) ush ON u.user_id = ush.user_id;
How many users subscribed in a given month?
sql
SELECT COUNT(DISTINCT user_id)
FROM user_subscription_history
WHERE current_subscription_start_date >= '2022-01-01' AND current_subscription_start_date < '2022-02-01';
What was the total revenue generated in a given month?
sql
SELECT SUM(subscription_price)
FROM user_subscription_history
WHERE current_subscription_start_date >= '2022-01-01' AND current_subscription_start_date < '2022-02-01' AND subscription_status = 'active';