MySQL中如何查找每組數(shù)據(jù)的前一個(gè)數(shù)據(jù)呢?可以使用LEAD() OVER()函數(shù)來實(shí)現(xiàn),具體實(shí)現(xiàn)方法如下:
SELECT *, LEAD(column_name) OVER (PARTITION BY group_column ORDER BY order_column) AS prev_value FROM table_name;
其中,column_name
是要查找前一個(gè)數(shù)據(jù)的列名,group_column
是數(shù)據(jù)分組的列,order_column
是要按照哪一列進(jìn)行排序。執(zhí)行上述代碼后,會(huì)返回每個(gè)分組的前一個(gè)數(shù)據(jù)。
下面是一個(gè)示例代碼:
SELECT *, LEAD(salary) OVER (PARTITION BY department ORDER BY hire_date) AS prev_salary FROM employees;
執(zhí)行以上代碼后,將返回每個(gè)部門員工的前一個(gè)員工的薪資。