Oracle LAG กับ LEAD SQL Command สำหรับ select ข้อมูลจาก row ก่อนหน้า หรือ ถัดไป
การ Query เพื่อนำข้อมูลของ Row ก่อนหน้า หรือ Row ถัดไป มาแสดงข้อมูลในแถวปจจุบัน
เพื่อใช้ในการคำนวณ หรือ การพิจารณาเหตุการณ์ ก่อนหน้า หรือ ถัดไปนั้นถือว่าน่าสนใจมาก
Oracle สามารถใช้คำสั่ง นี้ได้เลยครับ
LAG เพื่อดึงข้อมูลจาก Raw ก่อนหน้า
LEAD เพื่อดึงข้อมูลจาก Raw ถัดไป
รูปแบบคำสั่งจะเป็นแบบนี้
LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
ยกตัวอย่างเช่น เรามี ข้อมูลใน table ตามนี้
code_id | f1 | f2 |
1001 | f11 | f21 |
1002 | f12 | f22 |
1003 | f13 | f23 |
คำสั่ง Query
select code_id,f1 , f2 ,
LAG(f2) OVER (order by code_id) prv_f2,
LEAD(f2) OVER (order by code_id) next_f2
FROM my_table