Post Success After Failure
HardYou are given the following tables:
post table:
post_user table
Write a SQL that shows the success rate of post (%) when the user's previous post had failed.
Your output should have the following columns: user_id and next_post_sc_rate (success rate of post when user’s previous post had failed). Order results by increasing next_post_sc_rate.
“For each user, among posts that immediately follow a failed post, what percentage of those posts are successful?”
Formula (per user)
Q = the set of that user’s posts whose previous post (same user) failed
Successes = count of posts in Q that are successful
next_post_sc_rate = Successes/Q * 100
If a user ends with a failure and has no next post, that failure does not enter the denominator (because there is no “next post” to evaluate).
Build “previous outcome” per user (CTE)
-
Partition rows by
user_id;order each user’s posts bypost_date, post_id. -
Use
LAG(is_successful_post)to fetch the previous post’s outcome asprev_success. -
Output per row:
user_id,is_successful_post(this post), andprev_success(prior post). -
Result: each post knows whether the immediately prior post succeeded/failed.
Filter to next-after-failure & compute rate
-
Keep only rows
where prev_success = FALSE(posts that follow a failure). -
Convert success to 1, failure to 0 with
CASE; take AVG(...)to get successes ÷ qualifying posts. -
Multiply by 100 and ROUND(..., 2) to report a percentage as
next_post_sc_rate. -
GROUP BY user_idto get one rate per user;ORDER BYto sort ascending.