|
| 1 | +/* |
| 2 | +
|
| 3 | +Problem Link -> https://leetcode.com/problems/count-salary-categories/description/?envType=study-plan-v2&envId=top-sql-50 |
| 4 | +
|
| 5 | +------------------------------------------------------------- QUESTION ----------------------------------------------------------- |
| 6 | +
|
| 7 | +Table: Accounts |
| 8 | +
|
| 9 | ++-------------+------+ |
| 10 | +| Column Name | Type | |
| 11 | ++-------------+------+ |
| 12 | +| account_id | int | |
| 13 | +| income | int | |
| 14 | ++-------------+------+ |
| 15 | +account_id is the primary key (column with unique values) for this table. |
| 16 | +Each row contains information about the monthly income for one bank account. |
| 17 | + |
| 18 | +
|
| 19 | +Write a solution to calculate the number of bank accounts for each salary category. The salary categories are: |
| 20 | +"Low Salary": All the salaries strictly less than $20000. |
| 21 | +"Average Salary": All the salaries in the inclusive range [$20000, $50000]. |
| 22 | +"High Salary": All the salaries strictly greater than $50000. |
| 23 | +The result table must contain all three categories. If there are no accounts in a category, return 0. |
| 24 | +
|
| 25 | +Return the result table in any order. |
| 26 | +The result format is in the following example. |
| 27 | +
|
| 28 | + |
| 29 | +Example 1: |
| 30 | +
|
| 31 | +Input: |
| 32 | +Accounts table: |
| 33 | ++------------+--------+ |
| 34 | +| account_id | income | |
| 35 | ++------------+--------+ |
| 36 | +| 3 | 108939 | |
| 37 | +| 2 | 12747 | |
| 38 | +| 8 | 87709 | |
| 39 | +| 6 | 91796 | |
| 40 | ++------------+--------+ |
| 41 | +
|
| 42 | +Output: |
| 43 | ++----------------+----------------+ |
| 44 | +| category | accounts_count | |
| 45 | ++----------------+----------------+ |
| 46 | +| Low Salary | 1 | |
| 47 | +| Average Salary | 0 | |
| 48 | +| High Salary | 3 | |
| 49 | ++----------------+----------------+ |
| 50 | +
|
| 51 | +Explanation: |
| 52 | +Low Salary: Account 2. |
| 53 | +Average Salary: No accounts. |
| 54 | +High Salary: Accounts 3, 6, and 8. |
| 55 | +
|
| 56 | +*/ |
| 57 | + |
| 58 | +-- ----------------------------------------------------------- SOLUTION ----------------------------------------------------------- |
| 59 | + |
| 60 | +SELECT |
| 61 | + "Low Salary" AS category, |
| 62 | + SUM(income < 20000) AS accounts_count |
| 63 | +FROM Accounts |
| 64 | + |
| 65 | +UNION |
| 66 | + |
| 67 | +SELECT |
| 68 | + "Average Salary" AS category, |
| 69 | + SUM(income BETWEEN 20000 AND 50000) AS accounts_count |
| 70 | +FROM Accounts |
| 71 | + |
| 72 | +UNION |
| 73 | + |
| 74 | +SELECT |
| 75 | + "High Salary" AS category, |
| 76 | + SUM(income > 50000) AS accounts_count |
| 77 | +FROM Accounts |
| 78 | + |
0 commit comments