|
| 1 | +/* |
| 2 | +Question 1934. Confirmation Rate |
| 3 | +Link: https://leetcode.com/problems/confirmation-rate/description/?envType=study-plan-v2&envId=top-sql-50 |
| 4 | +
|
| 5 | +Table: Signups |
| 6 | +
|
| 7 | ++----------------+----------+ |
| 8 | +| Column Name | Type | |
| 9 | ++----------------+----------+ |
| 10 | +| user_id | int | |
| 11 | +| time_stamp | datetime | |
| 12 | ++----------------+----------+ |
| 13 | +user_id is the column of unique values for this table. |
| 14 | +Each row contains information about the signup time for the user with ID user_id. |
| 15 | + |
| 16 | +
|
| 17 | +Table: Confirmations |
| 18 | +
|
| 19 | ++----------------+----------+ |
| 20 | +| Column Name | Type | |
| 21 | ++----------------+----------+ |
| 22 | +| user_id | int | |
| 23 | +| time_stamp | datetime | |
| 24 | +| action | ENUM | |
| 25 | ++----------------+----------+ |
| 26 | +(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table. |
| 27 | +user_id is a foreign key (reference column) to the Signups table. |
| 28 | +action is an ENUM (category) of the type ('confirmed', 'timeout') |
| 29 | +Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout'). |
| 30 | + |
| 31 | +
|
| 32 | +The confirmation rate of a user is the number of 'confirmed' messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is 0. Round the confirmation rate to two decimal places. |
| 33 | +
|
| 34 | +Write a solution to find the confirmation rate of each user. |
| 35 | +
|
| 36 | +Return the result table in any order. |
| 37 | +*/ |
| 38 | + |
| 39 | +SELECT |
| 40 | + s.user_id, |
| 41 | + COALESCE(CASE |
| 42 | + WHEN c.user_id IS NULL THEN 0.00 |
| 43 | + ELSE ROUND(( |
| 44 | + SELECT COUNT(c2.user_id) |
| 45 | + FROM Confirmations AS c2 |
| 46 | + WHERE c2.action = 'confirmed' AND c2.user_id = s.user_id |
| 47 | + GROUP BY c2.user_id |
| 48 | + ) / COUNT(c.user_id)::numeric, 2) |
| 49 | + END, 0.00) AS confirmation_rate |
| 50 | +FROM Signups AS s |
| 51 | +LEFT JOIN |
| 52 | + Confirmations AS c |
| 53 | + ON s.user_id = c.user_id |
| 54 | +GROUP BY s.user_id, c.user_id |
0 commit comments