กลับมาอีกครั้ง [ไวมาก] ฮ่าๆๆ ก็คือ อยากทำเป็นซีรีย์แหละ รู้สึกสนุก มันท้าทายดีตอนทำ กะตั้งชื่อว่า “LeetCode The Series” ช่วงแรกๆ อาจจะเป็น SQL ก่อนนะ เดี๋ยว R กับ Python จะตามมาครับ
ครั้งนี้เลือกที่จะจิ้มโจทย์ 181. Employees Earning More Than Their Managers
ใครกันที่ได้ค่าจ้างมากกว่าผู้จัดการตัวเอง — เอาจริงดี๊ ?? ไปดูข้อมูลกันคร่าวๆ
Table: Employee
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| salary | int |
| managerId | int |
+-------------+---------+
- id is the primary key (column with unique values) for this table.
- Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.
- มี id เป็น PK แต่ละ Row เป็นข้อมูลของพนักงาน มีค่าจ้าง และ ID ของผู้จัดการตัวเอง
Output:
+----------+
| Employee |
+----------+
| Joe |
+----------+
Explanation: Joe is the only employee who earns more than his manager.
โจทย์: ⁉️ Write a solution to find the employees who earn more than their managers. [ใครที่ได้ค่าจ้างมากกว่าผู้จัดการตัวเอง?] Return the result table in any order. [คำตอบไม่จำเป็นต้องเรียงลำดับ]

แนวคิด: 🤔 หลังจากดูข้อมูลจะเห็นว่ามีอยู่ 1 คนที่เงินเดือนมากกว่าผู้จัดการคือ Joe แถมโจทย์ให้ data มาแค่ตารางเดียวอีก นี่เป็นคอนเซ็ปของ Self Join นี่นา แล้วก็ where เพิ่มว่า เงินเดือนใครมากกว่า ผู้จัดการก็ได้คำตอบแล้ว → ลงมือเลย
select
e1.name as Employee
from Employee e1, Employee e2
where e1.managerId = e2.id
and e1.salary > e2.salary;

เสร็จแล้ว ง่ายจนงง 😁✌️ ฮ่าๆๆ (ที่จริงโจทย์อยู่ในระดับ Easy) แต่เดี๋ยวจะลองยากขึ้นนะครับ เดี๋ยวเอามาฝากกันอีกยาวๆ เลย
Schema
Create table If Not Exists Employee (id int, name varchar(255), salary int, managerId int)
Truncate table Employee
insert into Employee (id, name, salary, managerId) values ('1', 'Joe', '70000', '3')
insert into Employee (id, name, salary, managerId) values ('2', 'Henry', '80000', '4')
insert into Employee (id, name, salary, managerId) values ('3', 'Sam', '60000', NULL)
insert into Employee (id, name, salary, managerId) values ('4', 'Max', '90000', NULL)
คุณผู้อ่านชอบมั้ยครับ คอมเม้นต์ให้คำแนะนำได้นะครับ
แปลผิดแปลถูก + มี typo ขออภัยครับ 🙏 จะพยายามให้ดีขึ้นครับ
.
ขอบคุณครับ






