楼主: Myron2017
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题记录帖子

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3421. Find Students Who Improved
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Scores

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| student_id  | int     |
| subject     | varchar |
| score       | int     |
| exam_date   | varchar |
+-------------+---------+
(student_id, subject, exam_date) is the primary key for this table.
Each row contains information about a student's score in a specific subject on a particular exam date. score is between 0 and 100 (inclusive).
Write a solution to find the students who have shown improvement. A student is considered to have shown improvement if they meet both of these conditions:

Have taken exams in the same subject on at least two different dates
Their latest score in that subject is higher than their first score
Return the result table ordered by student_id, subject in ascending order.

The result format is in the following example.



Example:

Input:

Scores table:

+------------+----------+-------+------------+
| student_id | subject  | score | exam_date  |
+------------+----------+-------+------------+
| 101        | Math     | 70    | 2023-01-15 |
| 101        | Math     | 85    | 2023-02-15 |
| 101        | Physics  | 65    | 2023-01-15 |
| 101        | Physics  | 60    | 2023-02-15 |
| 102        | Math     | 80    | 2023-01-15 |
| 102        | Math     | 85    | 2023-02-15 |
| 103        | Math     | 90    | 2023-01-15 |
| 104        | Physics  | 75    | 2023-01-15 |
| 104        | Physics  | 85    | 2023-02-15 |
+------------+----------+-------+------------+
Output:

+------------+----------+-------------+--------------+
| student_id | subject  | first_score | latest_score |
+------------+----------+-------------+--------------+
| 101        | Math     | 70          | 85           |
| 102        | Math     | 80          | 85           |
| 104        | Physics  | 75          | 85           |
+------------+----------+-------------+--------------+
Explanation:

Student 101 in Math: Improved from 70 to 85
Student 101 in Physics: No improvement (dropped from 65 to 60)
Student 102 in Math: Improved from 80 to 85
Student 103 in Math: Only one exam, not eligible
Student 104 in Physics: Improved from 75 to 85
Result table is ordered by student_id, subject.
  1. # Write your MySQL query statement below
  2. WITH ranked AS (
  3.     SELECT
  4.         student_id,
  5.         subject,
  6.         score,
  7.         ROW_NUMBER() OVER (
  8.             PARTITION BY student_id, subject
  9.             ORDER BY exam_date ASC
  10.         ) AS rn_asc,
  11.         ROW_NUMBER() OVER (
  12.             PARTITION BY student_id, subject
  13.             ORDER BY exam_date DESC
  14.         ) AS rn_desc
  15.     FROM Scores
  16. )
  17. SELECT
  18.     student_id,
  19.     subject,
  20.     MAX(CASE WHEN rn_asc  = 1 THEN score END) AS first_score,
  21.     MAX(CASE WHEN rn_desc = 1 THEN score END) AS latest_score
  22. FROM ranked
  23. GROUP BY student_id, subject
  24. HAVING COUNT(*) >= 2
  25.    AND MAX(CASE WHEN rn_desc = 1 THEN score END)
  26.      > MAX(CASE WHEN rn_asc  = 1 THEN score END)
  27. ORDER BY student_id, subject;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3436. Find Valid Emails
Easy
Topics
SQL Schema
Pandas Schema
Table: Users

+-----------------+---------+
| Column Name     | Type    |
+-----------------+---------+
| user_id         | int     |
| email           | varchar |
+-----------------+---------+
(user_id) is the unique key for this table.
Each row contains a user's unique ID and email address.
Write a solution to find all the valid email addresses. A valid email address meets the following criteria:

It contains exactly one @ symbol.
It ends with .com.
The part before the @ symbol contains only alphanumeric characters and underscores.
The part after the @ symbol and before .com contains a domain name that contains only letters.
Return the result table ordered by user_id in ascending order.



Example:

Input:

Users table:

+---------+---------------------+
| user_id | email               |
+---------+---------------------+
| 1       | alice@example.com   |
| 2       | bob_at_example.com  |
| 3       | charlie@example.net |
| 4       | david@domain.com    |
| 5       | eve@invalid         |
+---------+---------------------+
Output:

+---------+-------------------+
| user_id | email             |
+---------+-------------------+
| 1       | alice@example.com |
| 4       | david@domain.com  |
+---------+-------------------+
Explanation:

alice@example.com is valid because it contains one @, alice is alphanumeric, and example.com starts with a letter and ends with .com.
bob_at_example.com is invalid because it contains an underscore instead of an @.
charlie@example.net is invalid because the domain does not end with .com.
david@domain.com is valid because it meets all criteria.
eve@invalid is invalid because the domain does not end with .com.
Result table is ordered by user_id in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     user_id,
  4.     email
  5. FROM Users
  6. WHERE email REGEXP '^[A-Za-z0-9_]+@[A-Za-z]+\\.com
  7. ORDER BY user_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3451. Find Invalid IP Addresses
Hard
Topics
SQL Schema
Pandas Schema
Table:  logs

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| log_id      | int     |
| ip          | varchar |
| status_code | int     |
+-------------+---------+
log_id is the unique key for this table.
Each row contains server access log information including IP address and HTTP status code.
Write a solution to find invalid IP addresses. Each octet in an IP address contains between 1 and 3 digits. An IPv4 address is invalid if it meets any of these conditions:

Contains a number greater than 255 in any octet.
Has leading zeros in any octet (for example, 01.02.03.04).
Has fewer or more than 4 octets.
Return the result table ordered by invalid_count, ip in descending order respectively.

The result format is in the following example.



Example:

Input:

logs table:

+--------+---------------+-------------+
| log_id | ip            | status_code |
+--------+---------------+-------------+
| 1      | 192.168.1.1   | 200         |
| 2      | 256.1.2.3     | 404         |
| 3      | 192.168.001.1 | 200         |
| 4      | 192.168.1.1   | 200         |
| 5      | 192.168.1     | 500         |
| 6      | 256.1.2.3     | 404         |
| 7      | 192.168.001.1 | 200         |
+--------+---------------+-------------+
Output:

+---------------+--------------+
| ip            | invalid_count|
+---------------+--------------+
| 256.1.2.3     | 2            |
| 192.168.001.1 | 2            |
| 192.168.1     | 1            |
+---------------+--------------+
Explanation:

256.1.2.3 is invalid because 256 > 255
192.168.001.1 is invalid because of leading zeros
192.168.1 is invalid because it has only 3 octets
The output table is ordered by invalid_count, ip in descending order respectively.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     ip,
  4.     COUNT(*) AS invalid_count
  5. FROM logs
  6. WHERE ip NOT REGEXP
  7.   '^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])
  8. GROUP BY ip
  9. ORDER BY invalid_count DESC, ip DESC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3368. First Letter Capitalization
Hard
Topics
SQL Schema
Pandas Schema
Table: user_content

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| content_id  | int     |
| content_text| varchar |
+-------------+---------+
content_id is the unique key for this table.
Each row contains a unique ID and the corresponding text content.
Write a solution to transform the text in the content_text column by applying the following rules:

Convert the first letter of each word to uppercase
Keep all other letters in lowercase
Preserve all existing spaces
Note: There will be no special character in content_text.

Return the result table that includes both the original content_text and the modified text where each word starts with a capital letter.

The result format is in the following example.



Example:

Input:

user_content table:

+------------+-----------------------------------+
| content_id | content_text                      |
+------------+-----------------------------------+
| 1          | hello world of SQL                |
| 2          | the QUICK brown fox               |
| 3          | data science AND machine learning |
| 4          | TOP rated programming BOOKS       |
+------------+-----------------------------------+
Output:

+------------+-----------------------------------+-----------------------------------+
| content_id | original_text                     | converted_text                    |
+------------+-----------------------------------+-----------------------------------+
| 1          | hello world of SQL                | Hello World Of Sql                |
| 2          | the QUICK brown fox               | The Quick Brown Fox               |
| 3          | data science AND machine learning | Data Science And Machine Learning |
| 4          | TOP rated programming BOOKS       | Top Rated Programming Books       |
+------------+-----------------------------------+-----------------------------------+
Explanation:

For content_id = 1:
Each word's first letter is capitalized: Hello World Of Sql
For content_id = 2:
Original mixed-case text is transformed to title case: The Quick Brown Fox
For content_id = 3:
The word AND is converted to "And": "Data Science And Machine Learning"
For content_id = 4:
Handles word TOP rated correctly: Top Rated
Converts BOOKS from all caps to title case: Books
  1. # Write your MySQL query statement below
  2. WITH RECURSIVE build AS (
  3.     SELECT
  4.         content_id,
  5.         content_text,
  6.         1 AS i,
  7.         CAST('' AS CHAR(1000)) AS res
  8.     FROM user_content

  9.     UNION ALL

  10.     SELECT
  11.         content_id,
  12.         content_text,
  13.         i + 1,
  14.         CONCAT(
  15.             res,
  16.             CASE
  17.                 WHEN i = 1 OR SUBSTRING(content_text, i - 1, 1) = ' '
  18.                     THEN UPPER(SUBSTRING(content_text, i, 1))
  19.                 ELSE LOWER(SUBSTRING(content_text, i, 1))
  20.             END
  21.         )
  22.     FROM build
  23.     WHERE i <= CHAR_LENGTH(content_text)
  24. )
  25. SELECT
  26.     content_id,
  27.     content_text AS original_text,
  28.     res          AS converted_text
  29. FROM build
  30. WHERE i = CHAR_LENGTH(content_text) + 1
  31. ORDER BY content_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3374. First Letter Capitalization II
Hard
Topics
SQL Schema
Pandas Schema
Table: user_content

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| content_id   | int     |
| content_text | varchar |
+--------------+---------+
content_id is the unique key for this table.
Each row contains a unique ID and the corresponding text content.
A word is a maximal non-empty sequence of characters that does not contain a space.

Write a solution to transform the text in the content_text column by applying the following rules to each word:

If the word starts with a character that is not an English letter, leave the entire word unchanged.
Otherwise, if the word consists of two or more non-empty parts of English letters connected by hyphens -, convert the first letter of each part to uppercase and the remaining letters of each part to lowercase. For example, top-rated becomes Top-Rated and FR-ONT-end becomes Fr-Ont-End.
Otherwise, convert the first letter of the word to uppercase and all remaining English letters to lowercase. Any special characters remain unchanged.
All other formatting and spacing must remain unchanged.

Return the result table that includes both the original content_text and the modified text following the above rules.

The result format is in the following example.



Example:

Input:

user_content table:

+------------+---------------------------------+
| content_id | content_text                    |
+------------+---------------------------------+
| 1          | hello world of SQL              |
| 2          | the QUICK-brown fox             |
| 3          | modern-day DATA science         |
| 4          | web-based FRONT-end development |
+------------+---------------------------------+
Output:

+------------+---------------------------------+---------------------------------+
| content_id | original_text                   | converted_text                  |
+------------+---------------------------------+---------------------------------+
| 1          | hello world of SQL              | Hello World Of Sql              |
| 2          | the QUICK-brown fox             | The Quick-Brown Fox             |
| 3          | modern-day DATA science         | Modern-Day Data Science         |
| 4          | web-based FRONT-end development | Web-Based Front-End Development |
+------------+---------------------------------+---------------------------------+
Explanation:

For content_id = 1:
Each word's first letter is capitalized: "Hello World Of Sql".
For content_id = 2:
The hyphenated word "QUICK-brown" becomes "Quick-Brown".
Other words follow the normal capitalization rules.
For content_id = 3:
The hyphenated word "modern-day" becomes "Modern-Day".
"DATA" is converted to "Data".
For content_id = 4:
"web-based" becomes "Web-Based".
"FRONT-end" becomes "Front-End".


Constraints:

content_text contains only English letters, spaces, and the characters \, @, -, /, ^, and ,.
  1. # Write your MySQL query statement below
  2. WITH RECURSIVE build AS (
  3.     SELECT
  4.         content_id,
  5.         content_text,
  6.         1 AS i,
  7.         CASE
  8.             WHEN SUBSTRING_INDEX(content_text, ' ', 1) NOT REGEXP '^[A-Za-z]' THEN 0
  9.             WHEN SUBSTRING_INDEX(content_text, ' ', 1) REGEXP '^[A-Za-z]+(-[A-Za-z]+)+ THEN 2
  10.             ELSE 1
  11.         END AS m,
  12.         CAST('' AS CHAR(1000)) AS res
  13.     FROM user_content

  14.     UNION ALL

  15.     SELECT
  16.         content_id,
  17.         content_text,
  18.         i + 1,
  19.         CASE
  20.             WHEN SUBSTRING(content_text, i, 1) <> ' ' THEN m   -- still inside a word
  21.             WHEN SUBSTRING_INDEX(SUBSTRING(content_text, i + 1), ' ', 1) NOT REGEXP '^[A-Za-z]' THEN 0
  22.             WHEN SUBSTRING_INDEX(SUBSTRING(content_text, i + 1), ' ', 1) REGEXP '^[A-Za-z]+(-[A-Za-z]+)+ THEN 2
  23.             ELSE 1
  24.         END,
  25.         CONCAT(
  26.             res,
  27.             CASE
  28.                 WHEN m = 0 THEN SUBSTRING(content_text, i, 1)
  29.                 WHEN i = 1
  30.                   OR SUBSTRING(content_text, i - 1, 1) = ' '
  31.                   OR (m = 2 AND SUBSTRING(content_text, i - 1, 1) = '-')
  32.                     THEN UPPER(SUBSTRING(content_text, i, 1))
  33.                 ELSE LOWER(SUBSTRING(content_text, i, 1))
  34.             END
  35.         )
  36.     FROM build
  37.     WHERE i <= CHAR_LENGTH(content_text)
  38. )
  39. SELECT
  40.     content_id,
  41.     content_text AS original_text,
  42.     res          AS converted_text
  43. FROM build
  44. WHERE i = CHAR_LENGTH(content_text) + 1
  45. ORDER BY content_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3475. DNA Pattern Recognition
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Samples

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| sample_id      | int     |
| dna_sequence   | varchar |
| species        | varchar |
+----------------+---------+
sample_id is the unique key for this table.
Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from.
Biologists are studying basic patterns in DNA sequences. Write a solution to identify sample_id with the following patterns:

Sequences that start with ATG (a common start codon)
Sequences that end with either TAA, TAG, or TGA (stop codons)
Sequences containing the motif ATAT (a simple repeated pattern)
Sequences that have at least 3 consecutive G (like GGG or GGGG)
Return the result table ordered by sample_id in ascending order.

The result format is in the following example.



Example:

Input:

Samples table:

+-----------+------------------+-----------+
| sample_id | dna_sequence     | species   |
+-----------+------------------+-----------+
| 1         | ATGCTAGCTAGCTAA  | Human     |
| 2         | GGGTCAATCATC     | Human     |
| 3         | ATATATCGTAGCTA   | Human     |
| 4         | ATGGGGTCATCATAA  | Mouse     |
| 5         | TCAGTCAGTCAG     | Mouse     |
| 6         | ATATCGCGCTAG     | Zebrafish |
| 7         | CGTATGCGTCGTA    | Zebrafish |
+-----------+------------------+-----------+
Output:

+-----------+------------------+-------------+-------------+------------+------------+------------+
| sample_id | dna_sequence     | species     | has_start   | has_stop   | has_atat   | has_ggg    |
+-----------+------------------+-------------+-------------+------------+------------+------------+
| 1         | ATGCTAGCTAGCTAA  | Human       | 1           | 1          | 0          | 0          |
| 2         | GGGTCAATCATC     | Human       | 0           | 0          | 0          | 1          |
| 3         | ATATATCGTAGCTA   | Human       | 0           | 0          | 1          | 0          |
| 4         | ATGGGGTCATCATAA  | Mouse       | 1           | 1          | 0          | 1          |
| 5         | TCAGTCAGTCAG     | Mouse       | 0           | 0          | 0          | 0          |
| 6         | ATATCGCGCTAG     | Zebrafish   | 0           | 1          | 1          | 0          |
| 7         | CGTATGCGTCGTA    | Zebrafish   | 0           | 0          | 0          | 0          |
+-----------+------------------+-------------+-------------+------------+------------+------------+
Explanation:

Sample 1 (ATGCTAGCTAGCTAA):
Starts with ATG (has_start = 1)
Ends with TAA (has_stop = 1)
Does not contain ATAT (has_atat = 0)
Does not contain at least 3 consecutive 'G's (has_ggg = 0)
Sample 2 (GGGTCAATCATC):
Does not start with ATG (has_start = 0)
Does not end with TAA, TAG, or TGA (has_stop = 0)
Does not contain ATAT (has_atat = 0)
Contains GGG (has_ggg = 1)
Sample 3 (ATATATCGTAGCTA):
Does not start with ATG (has_start = 0)
Does not end with TAA, TAG, or TGA (has_stop = 0)
Contains ATAT (has_atat = 1)
Does not contain at least 3 consecutive 'G's (has_ggg = 0)
Sample 4 (ATGGGGTCATCATAA):
Starts with ATG (has_start = 1)
Ends with TAA (has_stop = 1)
Does not contain ATAT (has_atat = 0)
Contains GGGG (has_ggg = 1)
Sample 5 (TCAGTCAGTCAG):
Does not match any patterns (all fields = 0)
Sample 6 (ATATCGCGCTAG):
Does not start with ATG (has_start = 0)
Ends with TAG (has_stop = 1)
Starts with ATAT (has_atat = 1)
Does not contain at least 3 consecutive 'G's (has_ggg = 0)
Sample 7 (CGTATGCGTCGTA):
Does not start with ATG (has_start = 0)
Does not end with TAA, "TAG", or "TGA" (has_stop = 0)
Does not contain ATAT (has_atat = 0)
Does not contain at least 3 consecutive 'G's (has_ggg = 0)
Note:

The result is ordered by sample_id in ascending order
For each pattern, 1 indicates the pattern is present and 0 indicates it is not present
  1. # Write your MySQL query statement below
  2. SELECT
  3.     sample_id,
  4.     dna_sequence,
  5.     species,
  6.     dna_sequence LIKE 'ATG%'   AS has_start,
  7.     (dna_sequence LIKE '%TAA'
  8.      OR dna_sequence LIKE '%TAG'
  9.      OR dna_sequence LIKE '%TGA') AS has_stop,
  10.     dna_sequence LIKE '%ATAT%' AS has_atat,
  11.     dna_sequence LIKE '%GGG%'  AS has_ggg
  12. FROM Samples
  13. ORDER BY sample_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3497. Analyze Subscription Conversion
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: UserActivity

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| user_id          | int     |
| activity_date    | date    |
| activity_type    | varchar |
| activity_duration| int     |
+------------------+---------+
(user_id, activity_date, activity_type) is the unique key for this table.
activity_type is one of ('free_trial', 'paid', 'cancelled').
activity_duration is the number of minutes the user spent on the platform that day.
Each row represents a user's activity on a specific date.
A subscription service wants to analyze user behavior patterns. The company offers a 7-day free trial, after which users can subscribe to a paid plan or cancel. Write a solution to:

Find users who converted from free trial to paid subscription
Calculate each user's average daily activity duration during their free trial period (rounded to 2 decimal places)
Calculate each user's average daily activity duration during their paid subscription period (rounded to 2 decimal places)
Return the result table ordered by user_id in ascending order.

The result format is in the following example.



Example:

Input:

UserActivity table:

+---------+---------------+---------------+-------------------+
| user_id | activity_date | activity_type | activity_duration |
+---------+---------------+---------------+-------------------+
| 1       | 2023-01-01    | free_trial    | 45                |
| 1       | 2023-01-02    | free_trial    | 30                |
| 1       | 2023-01-05    | free_trial    | 60                |
| 1       | 2023-01-10    | paid          | 75                |
| 1       | 2023-01-12    | paid          | 90                |
| 1       | 2023-01-15    | paid          | 65                |
| 2       | 2023-02-01    | free_trial    | 55                |
| 2       | 2023-02-03    | free_trial    | 25                |
| 2       | 2023-02-07    | free_trial    | 50                |
| 2       | 2023-02-10    | cancelled     | 0                 |
| 3       | 2023-03-05    | free_trial    | 70                |
| 3       | 2023-03-06    | free_trial    | 60                |
| 3       | 2023-03-08    | free_trial    | 80                |
| 3       | 2023-03-12    | paid          | 50                |
| 3       | 2023-03-15    | paid          | 55                |
| 3       | 2023-03-20    | paid          | 85                |
| 4       | 2023-04-01    | free_trial    | 40                |
| 4       | 2023-04-03    | free_trial    | 35                |
| 4       | 2023-04-05    | paid          | 45                |
| 4       | 2023-04-07    | cancelled     | 0                 |
+---------+---------------+---------------+-------------------+
Output:

+---------+--------------------+-------------------+
| user_id | trial_avg_duration | paid_avg_duration |
+---------+--------------------+-------------------+
| 1       | 45.00              | 76.67             |
| 3       | 70.00              | 63.33             |
| 4       | 37.50              | 45.00             |
+---------+--------------------+-------------------+
Explanation:

User 1:
Had 3 days of free trial with durations of 45, 30, and 60 minutes.
Average trial duration: (45 + 30 + 60) / 3 = 45.00 minutes.
Had 3 days of paid subscription with durations of 75, 90, and 65 minutes.
Average paid duration: (75 + 90 + 65) / 3 = 76.67 minutes.
User 2:
Had 3 days of free trial with durations of 55, 25, and 50 minutes.
Average trial duration: (55 + 25 + 50) / 3 = 43.33 minutes.
Did not convert to a paid subscription (only had free_trial and cancelled activities).
Not included in the output because they didn't convert to paid.
User 3:
Had 3 days of free trial with durations of 70, 60, and 80 minutes.
Average trial duration: (70 + 60 + 80) / 3 = 70.00 minutes.
Had 3 days of paid subscription with durations of 50, 55, and 85 minutes.
Average paid duration: (50 + 55 + 85) / 3 = 63.33 minutes.
User 4:
Had 2 days of free trial with durations of 40 and 35 minutes.
Average trial duration: (40 + 35) / 2 = 37.50 minutes.
Had 1 day of paid subscription with duration of 45 minutes before cancelling.
Average paid duration: 45.00 minutes.
The result table only includes users who converted from free trial to paid subscription (users 1, 3, and 4), and is ordered by user_id in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     user_id,
  4.     ROUND(AVG(CASE WHEN activity_type = 'free_trial' THEN activity_duration END), 2) AS trial_avg_duration,
  5.     ROUND(AVG(CASE WHEN activity_type = 'paid'       THEN activity_duration END), 2) AS paid_avg_duration
  6. FROM UserActivity
  7. GROUP BY user_id
  8. HAVING SUM(activity_type = 'free_trial') > 0
  9.    AND SUM(activity_type = 'paid')       > 0
  10. ORDER BY user_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3482. Analyze Organization Hierarchy
Hard
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Employees

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| employee_id    | int     |
| employee_name  | varchar |
| manager_id     | int     |
| salary         | int     |
| department     | varchar |
+----------------+----------+
employee_id is the unique key for this table.
Each row contains information about an employee, including their ID, name, their manager's ID, salary, and department.
manager_id is null for the top-level manager (CEO).
Write a solution to analyze the organizational hierarchy and answer the following:

Hierarchy Levels: For each employee, determine their level in the organization (CEO is level 1, employees reporting directly to the CEO are level 2, and so on).
Team Size: For each employee who is a manager, count the total number of employees under them (direct and indirect reports).
Salary Budget: For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).
Return the result table ordered by the result ordered by level in ascending order, then by budget in descending order, and finally by employee_name in ascending order.

The result format is in the following example.



Example:

Input:

Employees table:

+-------------+---------------+------------+--------+-------------+
| employee_id | employee_name | manager_id | salary | department  |
+-------------+---------------+------------+--------+-------------+
| 1           | Alice         | null       | 12000  | Executive   |
| 2           | Bob           | 1          | 10000  | Sales       |
| 3           | Charlie       | 1          | 10000  | Engineering |
| 4           | David         | 2          | 7500   | Sales       |
| 5           | Eva           | 2          | 7500   | Sales       |
| 6           | Frank         | 3          | 9000   | Engineering |
| 7           | Grace         | 3          | 8500   | Engineering |
| 8           | Hank          | 4          | 6000   | Sales       |
| 9           | Ivy           | 6          | 7000   | Engineering |
| 10          | Judy          | 6          | 7000   | Engineering |
+-------------+---------------+------------+--------+-------------+
Output:

+-------------+---------------+-------+-----------+--------+
| employee_id | employee_name | level | team_size | budget |
+-------------+---------------+-------+-----------+--------+
| 1           | Alice         | 1     | 9         | 84500  |
| 3           | Charlie       | 2     | 4         | 41500  |
| 2           | Bob           | 2     | 3         | 31000  |
| 6           | Frank         | 3     | 2         | 23000  |
| 4           | David         | 3     | 1         | 13500  |
| 7           | Grace         | 3     | 0         | 8500   |
| 5           | Eva           | 3     | 0         | 7500   |
| 9           | Ivy           | 4     | 0         | 7000   |
| 10          | Judy          | 4     | 0         | 7000   |
| 8           | Hank          | 4     | 0         | 6000   |
+-------------+---------------+-------+-----------+--------+
Explanation:

Organization Structure:
Alice (ID: 1) is the CEO (level 1) with no manager
Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)
David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)
Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)
Level Calculation:
The CEO (Alice) is at level 1
Each subsequent level of management adds 1 to the level
Team Size Calculation:
Alice has 9 employees under her (the entire company except herself)
Bob has 3 employees (David, Eva, and Hank)
Charlie has 4 employees (Frank, Grace, Ivy, and Judy)
David has 1 employee (Hank)
Frank has 2 employees (Ivy and Judy)
Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)
Budget Calculation:
Alice's budget: Her salary (12000) + all employees' salaries (72500) = 84500
Charlie's budget: His salary (10000) + Frank's budget (23000) + Grace's salary (8500) = 41500
Bob's budget: His salary (10000) + David's budget (13500) + Eva's salary (7500) = 31000
Frank's budget: His salary (9000) + Ivy's salary (7000) + Judy's salary (7000) = 23000
David's budget: His salary (7500) + Hank's salary (6000) = 13500
Employees with no direct reports have budgets equal to their own salary
Note:

The result is ordered first by level in ascending order
Within the same level, employees are ordered by budget in descending order then by name in ascending order
  1. # Write your MySQL query statement below
  2. WITH RECURSIVE closure AS (
  3.     SELECT employee_id AS anc, employee_id AS des
  4.     FROM Employees

  5.     UNION ALL

  6.     SELECT c.anc, e.employee_id
  7.     FROM closure c
  8.     JOIN Employees e
  9.       ON e.manager_id = c.des
  10. ),
  11. levels AS (
  12.     SELECT des AS employee_id, COUNT(*) AS level
  13.     FROM closure
  14.     GROUP BY des
  15. ),
  16. stats AS (
  17.     SELECT
  18.         c.anc            AS employee_id,
  19.         COUNT(*) - 1     AS team_size,
  20.         SUM(e.salary)    AS budget
  21.     FROM closure c
  22.     JOIN Employees e
  23.       ON e.employee_id = c.des
  24.     GROUP BY c.anc
  25. )
  26. SELECT
  27.     e.employee_id,
  28.     e.employee_name,
  29.     l.level,
  30.     s.team_size,
  31.     s.budget
  32. FROM Employees e
  33. JOIN levels l ON l.employee_id = e.employee_id
  34. JOIN stats  s ON s.employee_id = e.employee_id
  35. ORDER BY l.level ASC, s.budget DESC, e.employee_name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3832. Find Users with Persistent Behavior Patterns
Hard
SQL Schema
Pandas Schema
Table: activity

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| action_date  | date    |
| action       | varchar |
+--------------+---------+
(user_id, action_date, action) is the primary key (unique value) for this table.
Each row represents a user performing a specific action on a given date.
Write a solution to identify behaviorally stable users based on the following definition:

A user is considered behaviorally stable if there exists a sequence of at least 5 consecutive days such that:
The user performed exactly one action per day during that period.
The action is the same on all those consecutive days.
If a user has multiple qualifying sequences, only consider the sequence with the maximum length.
If multiple qualifying sequences have the same maximum length, consider the sequence with the lexicographically smallest action. If there is still a tie, consider the sequence with the latest start date.
Return the result table ordered by streak_length in descending order, then by user_id in ascending order.

The result format is in the following example.



Example:

Input:

activity table:

+---------+-------------+--------+
| user_id | action_date | action |
+---------+-------------+--------+
| 1       | 2024-01-01  | login  |
| 1       | 2024-01-02  | login  |
| 1       | 2024-01-03  | login  |
| 1       | 2024-01-04  | login  |
| 1       | 2024-01-05  | login  |
| 1       | 2024-01-06  | logout |
| 2       | 2024-01-01  | click  |
| 2       | 2024-01-02  | click  |
| 2       | 2024-01-03  | click  |
| 2       | 2024-01-04  | click  |
| 3       | 2024-01-01  | view   |
| 3       | 2024-01-02  | view   |
| 3       | 2024-01-03  | view   |
| 3       | 2024-01-04  | view   |
| 3       | 2024-01-05  | view   |
| 3       | 2024-01-06  | view   |
| 3       | 2024-01-07  | view   |
+---------+-------------+--------+
Output:

+---------+--------+---------------+------------+------------+
| user_id | action | streak_length | start_date | end_date   |
+---------+--------+---------------+------------+------------+
| 3       | view   | 7             | 2024-01-01 | 2024-01-07 |
| 1       | login  | 5             | 2024-01-01 | 2024-01-05 |
+---------+--------+---------------+------------+------------+
Explanation:

User 1:
Performed login from 2024-01-01 to 2024-01-05 on consecutive days
Each day has exactly one action, and the action is the same
Streak length = 5 (meets minimum requirement)
The action changes on 2024-01-06, ending the streak
User 2:
Performed click for only 4 consecutive days
Does not meet the minimum streak length of 5
Excluded from the result
User 3:
Performed view for 7 consecutive days
This is the longest valid sequence for this user
Included in the result
The Results table is ordered by streak_length in descending order, then by user_id in ascending order
  1. # Write your MySQL query statement below
  2. WITH single_day AS (
  3.     SELECT user_id, action_date, MIN(action) AS action
  4.     FROM activity
  5.     GROUP BY user_id, action_date
  6.     HAVING COUNT(*) = 1
  7. ),
  8. numbered AS (
  9.     SELECT
  10.         user_id,
  11.         action_date,
  12.         action,
  13.         ROW_NUMBER() OVER (
  14.             PARTITION BY user_id, action
  15.             ORDER BY action_date
  16.         ) AS rn
  17.     FROM single_day
  18. ),
  19. streaks AS (
  20.     SELECT
  21.         user_id,
  22.         action,
  23.         COUNT(*)         AS streak_length,
  24.         MIN(action_date) AS start_date,
  25.         MAX(action_date) AS end_date
  26.     FROM numbered
  27.     GROUP BY user_id, action, DATE_SUB(action_date, INTERVAL rn DAY)
  28.     HAVING COUNT(*) >= 5
  29. ),
  30. ranked AS (
  31.     SELECT
  32.         *,
  33.         ROW_NUMBER() OVER (
  34.             PARTITION BY user_id
  35.             ORDER BY streak_length DESC, action ASC, start_date DESC
  36.         ) AS rk
  37.     FROM streaks
  38. )
  39. SELECT user_id, action, streak_length, start_date, end_date
  40. FROM ranked
  41. WHERE rk = 1
  42. ORDER BY streak_length DESC, user_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3808. Find Emotionally Consistent Users
Medium
SQL Schema
Pandas Schema
Table: reactions

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| content_id   | int     |
| reaction     | varchar |
+--------------+---------+
(user_id, content_id) is the primary key (unique value) for this table.
Each row represents a reaction given by a user to a piece of content.
Write a solution to identify emotionally consistent users based on the following requirements:

For each user, count the total number of reactions they have given.
Only include users who have reacted to at least 5 different content items.
A user is considered emotionally consistent if at least 60% of their reactions are of the same type.
Return the result table ordered by reaction_ratio in descending order and then by user_id in ascending order.

Note:

reaction_ratio should be rounded to 2 decimal places
The result format is in the following example.



Example:

Input:

reactions table:

+---------+------------+----------+
| user_id | content_id | reaction |
+---------+------------+----------+
| 1       | 101        | like     |
| 1       | 102        | like     |
| 1       | 103        | like     |
| 1       | 104        | wow      |
| 1       | 105        | like     |
| 2       | 201        | like     |
| 2       | 202        | wow      |
| 2       | 203        | sad      |
| 2       | 204        | like     |
| 2       | 205        | wow      |
| 3       | 301        | love     |
| 3       | 302        | love     |
| 3       | 303        | love     |
| 3       | 304        | love     |
| 3       | 305        | love     |
+---------+------------+----------+
Output:

+---------+-------------------+----------------+
| user_id | dominant_reaction | reaction_ratio |
+---------+-------------------+----------------+
| 3       | love              | 1.00           |
| 1       | like              | 0.80           |
+---------+-------------------+----------------+
Explanation:

User 1:
Total reactions = 5
like appears 4 times
reaction_ratio = 4 / 5 = 0.80
Meets the 60% consistency requirement
User 2:
Total reactions = 5
Most frequent reaction appears only 2 times
reaction_ratio = 2 / 5 = 0.40
Does not meet the consistency requirement
User 3:
Total reactions = 5
'love' appears 5 times
reaction_ratio = 5 / 5 = 1.00
Meets the consistency requirement
The Results table is ordered by reaction_ratio in descending order, then by user_id in ascending order.
  1. # Write your MySQL query statement below
  2. WITH per_reaction AS (
  3.     SELECT
  4.         user_id,
  5.         reaction,
  6.         COUNT(*) AS cnt,
  7.         SUM(COUNT(*)) OVER (PARTITION BY user_id) AS total
  8.     FROM reactions
  9.     GROUP BY user_id, reaction
  10. ),
  11. ranked AS (
  12.     SELECT
  13.         *,
  14.         ROW_NUMBER() OVER (
  15.             PARTITION BY user_id
  16.             ORDER BY cnt DESC, reaction ASC
  17.         ) AS rn
  18.     FROM per_reaction
  19. )
  20. SELECT
  21.     user_id,
  22.     reaction            AS dominant_reaction,
  23.     ROUND(cnt / total, 2) AS reaction_ratio
  24. FROM ranked
  25. WHERE rn = 1
  26.   AND total >= 5
  27.   AND cnt * 5 >= total * 3
  28. ORDER BY reaction_ratio DESC, user_id ASC;
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表