🚀 Kosol.net

Published

- 1 min read

SQL RowNumber()

img of SQL RowNumber()

การใช้คำสั่ง ROWNUMBER ใน SQL Server

ขอยกตัวอย่างตาราง EmployeeCard ที่เก็บข้อมูลรหัสพนักงาน, หมายเลขบัตร และวันที่แก้ไขล่าสุด โดยจะมีการเพิ่มบัตรใหม่เข้าไปในตารางนี้ได้เรื่อยๆ โดยมีข้อมูลตัวอย่างดังนี้

   | EmpCode | CardID | ModifiedDate |
| ------- | ------ | ------------ |
| E0001   | 12345  | 20230101     |
| E0001   | 67890  | 20230201     |
| E0002   | 54321  | 20230101     |
| E0002   | 98765  | 20230201     |
| E0002   | 11111  | 20230301     |
| E0003   | 22222  | 20230101     |
| E0003   | 33333  | 20230201     |

โดยโจทย์ต้องการได้หมายเลขบัตร ที่มีการแก้ไขล่าสุดออกมาคนละ 1 แถว ดังนี้

   | EmpCode | CardID | ModifiedDate |
| ------- | ------ | ------------ |
| E0001   | 67890  | 20230201     |
| E0002   | 11111  | 20230301     |
| E0003   | 33333  | 20230201     |

In this example, the input data includes employee codes (EmpCode), card numbers (CardID), and the most recent modification dates (ModifiedDate). There are cases where the same employee code has multiple rows, each with a different card number.

   WITH RankedData AS (
  SELECT EmpCode, CardID, ModifiedDate,
    ROW_NUMBER() OVER (PARTITION BY EmpCode ORDER BY ModifiedDate DESC) AS RowNum
  FROM EmployeeCard
)
SELECT EmpCode, CardID, ModifiedDate
FROM RankedData
WHERE RowNum = 1;

ในที่นี้, เราใช้ SQL query ที่รวมกับ ROW_NUMBER() และ PARTITION BY เพื่อดึงข้อมูลที่มีการแก้ไขล่าสุดสำหรับแต่ละ EmpCode วิธีนี้ช่วยเพิ่มประสิทธิภาพในการค้นหาข้อมูลได้