Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dfa5952

Browse files
Merge pull request #93 from iamAntimPal/Branch-1
Branch 1
2 parents 8e5c702 + 7cfa939 commit dfa5952

File tree

3 files changed

+485
-0
lines changed
  • LeetCode SQL 50 Solution

3 files changed

+485
-0
lines changed
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# 🏢 Primary Department for Each Employee - LeetCode 1789
2+
3+
## 📌 Problem Statement
4+
You are given a table **Employee** that contains the following columns:
5+
6+
- **employee_id**: The ID of the employee.
7+
- **department_id**: The ID of the department to which the employee belongs.
8+
- **primary_flag**: An ENUM ('Y', 'N').
9+
- If `primary_flag` is `'Y'`, then the department is the primary department for that employee.
10+
- If `primary_flag` is `'N'`, then the department is not primary.
11+
12+
**Note:**
13+
- An employee can belong to multiple departments. When an employee joins multiple departments, they decide which one is their primary (set to `'Y'`).
14+
- If an employee belongs to only one department, then their `primary_flag` is `'N'`, but that department is still considered their primary department.
15+
16+
Your task is to **report all employees with their primary department**.
17+
For employees who belong to only one department, report that department.
18+
19+
Return the result table in **any order**.
20+
21+
---
22+
23+
## 📊 Table Structure
24+
25+
### **Employee Table**
26+
| Column Name | Type |
27+
| ------------- | ------- |
28+
| employee_id | int |
29+
| department_id | int |
30+
| primary_flag | varchar |
31+
32+
- `(employee_id, department_id)` is the **primary key** for this table.
33+
34+
---
35+
36+
## 📊 Example 1:
37+
38+
### **Input:**
39+
#### **Employee Table**
40+
| employee_id | department_id | primary_flag |
41+
| ----------- | ------------- | ------------ |
42+
| 1 | 1 | N |
43+
| 2 | 1 | Y |
44+
| 2 | 2 | N |
45+
| 3 | 3 | N |
46+
| 4 | 2 | N |
47+
| 4 | 3 | Y |
48+
| 4 | 4 | N |
49+
50+
### **Output:**
51+
| employee_id | department_id |
52+
| ----------- | ------------- |
53+
| 1 | 1 |
54+
| 2 | 1 |
55+
| 3 | 3 |
56+
| 4 | 3 |
57+
58+
### **Explanation:**
59+
- **Employee 1** belongs to only one department (1), so department 1 is their primary.
60+
- **Employee 2** belongs to departments 1 and 2. The row with `primary_flag = 'Y'` indicates that department 1 is their primary.
61+
- **Employee 3** belongs only to department 3.
62+
- **Employee 4** belongs to departments 2, 3, and 4. The row with `primary_flag = 'Y'` indicates that department 3 is their primary.
63+
64+
---
65+
66+
## 🖥 SQL Solution
67+
68+
### **Approach:**
69+
- **Step 1:** For employees who have `primary_flag = 'Y'`, choose those rows.
70+
- **Step 2:** For employees who belong to only one department, return that row.
71+
- Combine the results using `UNION DISTINCT`.
72+
73+
```sql
74+
SELECT employee_id, department_id
75+
FROM Employee
76+
WHERE primary_flag = 'Y'
77+
UNION DISTINCT
78+
SELECT employee_id, department_id
79+
FROM Employee
80+
GROUP BY employee_id
81+
HAVING COUNT(*) = 1;
82+
```
83+
84+
---
85+
86+
## 🐍 Python (Pandas) Solution
87+
88+
### **Approach:**
89+
1. **Group** the DataFrame by `employee_id`.
90+
2. For each group:
91+
- If any row has `primary_flag == 'Y'`, choose the first such row.
92+
- Otherwise (i.e., employee belongs to only one department), choose that row.
93+
3. Return the resulting DataFrame with only `employee_id` and `department_id`.
94+
95+
```python
96+
import pandas as pd
97+
98+
def primary_department(employees: pd.DataFrame) -> pd.DataFrame:
99+
def select_primary(group):
100+
# If there's any row with primary_flag 'Y', choose the first one
101+
if (group['primary_flag'] == 'Y').any():
102+
return group[group['primary_flag'] == 'Y'].iloc[0]
103+
else:
104+
# For employees with only one department
105+
return group.iloc[0]
106+
107+
result = employees.groupby('employee_id').apply(select_primary).reset_index(drop=True)
108+
return result[['employee_id', 'department_id']]
109+
```
110+
111+
---
112+
113+
## 📁 File Structure
114+
```
115+
📂 Primary-Department
116+
│── README.md
117+
│── solution.sql
118+
│── solution_pandas.py
119+
│── test_cases.sql
120+
│── sample_data.csv
121+
```
122+
123+
---
124+
125+
## 🔗 Useful Links
126+
- 📖 [LeetCode Problem](https://leetcode.com/problems/primary-department-for-each-employee/)
127+
- 🔍 [MySQL UNION Operator](https://www.w3schools.com/sql/sql_union.asp)
128+
- 🐍 [Pandas GroupBy Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html)
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
# 💰 Count Salary Categories - LeetCode 907
2+
3+
## 📌 Problem Statement
4+
You are given a table **Accounts** that contains information about bank accounts, including their monthly income.
5+
Your task is to calculate the number of bank accounts in each salary category.
6+
7+
The salary categories are defined as follows:
8+
- **"Low Salary"**: Salaries strictly less than \$20,000.
9+
- **"Average Salary"**: Salaries in the inclusive range [\$20,000, \$50,000].
10+
- **"High Salary"**: Salaries strictly greater than \$50,000.
11+
12+
The result table must contain **all three categories**. If there are no accounts in a category, return 0.
13+
14+
Return the result in **any order**.
15+
16+
---
17+
18+
## 📊 Table Structure
19+
20+
### **Accounts Table**
21+
| Column Name | Type |
22+
| ----------- | ---- |
23+
| account_id | int |
24+
| income | int |
25+
26+
- `account_id` is the **primary key** for this table.
27+
- Each row contains the monthly income for one bank account.
28+
29+
---
30+
31+
## 📊 Example 1:
32+
33+
### **Input:**
34+
#### **Accounts Table**
35+
| account_id | income |
36+
| ---------- | ------ |
37+
| 3 | 108939 |
38+
| 2 | 12747 |
39+
| 8 | 87709 |
40+
| 6 | 91796 |
41+
42+
### **Output:**
43+
| category | accounts_count |
44+
| -------------- | -------------- |
45+
| Low Salary | 1 |
46+
| Average Salary | 0 |
47+
| High Salary | 3 |
48+
49+
### **Explanation:**
50+
- **Low Salary**: Account with income 12747.
51+
- **Average Salary**: No accounts have an income in the range [20000, 50000].
52+
- **High Salary**: Accounts with incomes 108939, 87709, and 91796.
53+
54+
---
55+
56+
## 🖥 SQL Solution
57+
58+
### **Approach:**
59+
1. **CTE "S"**: Create a static table with the three salary categories.
60+
```sql
61+
WITH S AS (
62+
SELECT 'Low Salary' AS category
63+
UNION
64+
SELECT 'Average Salary'
65+
UNION
66+
SELECT 'High Salary'
67+
),
68+
```
69+
- This defines the three salary categories to ensure every category appears in the final result.
70+
71+
2. **CTE "T"**: Categorize each account from the **Accounts** table using a `CASE` statement and count the number of accounts in each category.
72+
```sql
73+
T AS (
74+
SELECT
75+
CASE
76+
WHEN income < 20000 THEN 'Low Salary'
77+
WHEN income > 50000 THEN 'High Salary'
78+
ELSE 'Average Salary'
79+
END AS category,
80+
COUNT(1) AS accounts_count
81+
FROM Accounts
82+
GROUP BY 1
83+
)
84+
```
85+
- The `CASE` statement assigns a salary category based on the income.
86+
- `COUNT(1)` counts the number of accounts in each category.
87+
88+
3. **Final SELECT with LEFT JOIN**: Combine the static category table `S` with the computed counts from `T` to ensure every category is included, using `IFNULL` to convert any missing count to 0.
89+
```sql
90+
SELECT S.category, IFNULL(T.accounts_count, 0) AS accounts_count
91+
FROM S
92+
LEFT JOIN T USING (category);
93+
```
94+
95+
### **Complete SQL Query:**
96+
```sql
97+
WITH S AS (
98+
SELECT 'Low Salary' AS category
99+
UNION
100+
SELECT 'Average Salary'
101+
UNION
102+
SELECT 'High Salary'
103+
),
104+
T AS (
105+
SELECT
106+
CASE
107+
WHEN income < 20000 THEN 'Low Salary'
108+
WHEN income > 50000 THEN 'High Salary'
109+
ELSE 'Average Salary'
110+
END AS category,
111+
COUNT(1) AS accounts_count
112+
FROM Accounts
113+
GROUP BY 1
114+
)
115+
SELECT S.category, IFNULL(T.accounts_count, 0) AS accounts_count
116+
FROM S
117+
LEFT JOIN T USING (category);
118+
```
119+
120+
---
121+
122+
## 🐍 Python (Pandas) Solution
123+
124+
### **Approach:**
125+
1. **Categorize Accounts**: Create a new column `category` in the DataFrame by applying the salary conditions.
126+
2. **Group and Count**: Group by the `category` column and count the number of accounts.
127+
3. **Merge with Static Categories**: Ensure all three salary categories appear by merging with a predefined DataFrame that contains all categories, filling missing counts with 0.
128+
129+
```python
130+
import pandas as pd
131+
132+
def count_salary_categories(accounts: pd.DataFrame) -> pd.DataFrame:
133+
# Define the salary categorization function
134+
def categorize(income):
135+
if income < 20000:
136+
return 'Low Salary'
137+
elif income > 50000:
138+
return 'High Salary'
139+
else:
140+
return 'Average Salary'
141+
142+
# Apply categorization
143+
accounts['category'] = accounts['income'].apply(categorize)
144+
145+
# Count accounts in each category
146+
counts = accounts.groupby('category').size().reset_index(name='accounts_count')
147+
148+
# Define static categories DataFrame
149+
categories = pd.DataFrame({
150+
'category': ['Low Salary', 'Average Salary', 'High Salary']
151+
})
152+
153+
# Merge to ensure all categories are present, fill missing values with 0
154+
result = categories.merge(counts, on='category', how='left')
155+
result['accounts_count'] = result['accounts_count'].fillna(0).astype(int)
156+
157+
return result
158+
159+
# Example usage:
160+
# df = pd.read_csv("sample_accounts.csv")
161+
# print(count_salary_categories(df))
162+
```
163+
164+
---
165+
166+
## 📁 File Structure
167+
```
168+
📂 Count-Salary-Categories
169+
│── README.md
170+
│── solution.sql
171+
│── solution_pandas.py
172+
│── test_cases.sql
173+
│── sample_accounts.csv
174+
```
175+
176+
---
177+
178+
## 🔗 Useful Links
179+
- 📖 [LeetCode Problem](https://leetcode.com/problems/count-salary-categories/)
180+
- 📝 [MySQL WITH Clause (CTE)](https://www.w3schools.com/sql/sql_with.asp)
181+
- 🔍 [MySQL IFNULL Function](https://www.w3schools.com/sql/func_mysql_ifnull.asp)
182+
- 🐍 [Pandas GroupBy Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html)
183+
```
184+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /