|
| 1 | +907. Count Salary Categories |
| 2 | +Solved |
| 3 | +Medium |
| 4 | +Topics |
| 5 | +Companies |
| 6 | +SQL Schema |
| 7 | +Pandas Schema |
| 8 | +Table: Accounts |
| 9 | + |
| 10 | ++-------------+------+ |
| 11 | +| Column Name | Type | |
| 12 | ++-------------+------+ |
| 13 | +| account_id | int | |
| 14 | +| income | int | |
| 15 | ++-------------+------+ |
| 16 | +account_id is the primary key (column with unique values) for this table. |
| 17 | +Each row contains information about the monthly income for one bank account. |
| 18 | + |
| 19 | + |
| 20 | +Write a solution to calculate the number of bank accounts for each salary category. The salary categories are: |
| 21 | + |
| 22 | +"Low Salary": All the salaries strictly less than $20000. |
| 23 | +"Average Salary": All the salaries in the inclusive range [$20000, $50000]. |
| 24 | +"High Salary": All the salaries strictly greater than $50000. |
| 25 | +The result table must contain all three categories. If there are no accounts in a category, return 0. |
| 26 | + |
| 27 | +Return the result table in any order. |
| 28 | + |
| 29 | +The result format is in the following example. |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +Example 1: |
| 34 | + |
| 35 | +Input: |
| 36 | +Accounts table: |
| 37 | ++------------+--------+ |
| 38 | +| account_id | income | |
| 39 | ++------------+--------+ |
| 40 | +| 3 | 108939 | |
| 41 | +| 2 | 12747 | |
| 42 | +| 8 | 87709 | |
| 43 | +| 6 | 91796 | |
| 44 | ++------------+--------+ |
| 45 | +Output: |
| 46 | ++----------------+----------------+ |
| 47 | +| category | accounts_count | |
| 48 | ++----------------+----------------+ |
| 49 | +| Low Salary | 1 | |
| 50 | +| Average Salary | 0 | |
| 51 | +| High Salary | 3 | |
| 52 | ++----------------+----------------+ |
| 53 | +Explanation: |
| 54 | +Low Salary: Account 2. |
| 55 | +Average Salary: No accounts. |
| 56 | +High Salary: Accounts 3, 6, and 8. |
| 57 | + |
| 58 | + |
| 59 | +# Write your MySQL query statement below |
| 60 | +WITH |
| 61 | + S AS ( |
| 62 | + SELECT 'Low Salary' AS category |
| 63 | + UNION |
| 64 | + SELECT 'Average Salary' |
| 65 | + UNION |
| 66 | + SELECT 'High Salary' |
| 67 | + ), |
| 68 | + T AS ( |
| 69 | + SELECT |
| 70 | + CASE |
| 71 | + WHEN income < 20000 THEN "Low Salary" |
| 72 | + WHEN income > 50000 THEN 'High Salary' |
| 73 | + ELSE 'Average Salary' |
| 74 | + END AS category, |
| 75 | + COUNT(1) AS accounts_count |
| 76 | + FROM Accounts |
| 77 | + GROUP BY 1 |
| 78 | + ) |
| 79 | +SELECT category, IFNULL(accounts_count, 0) AS accounts_count |
| 80 | +FROM |
| 81 | + S |
| 82 | + LEFT JOIN T USING (category); |
| 83 | + |
0 commit comments