Retrieve the previous employee's salary within each department, ordered by employee ID, and use 0 as the default value if there is no previous salary.
CREATE TABLE employees (emp_id INTEGER, dept_id INTEGER, salary INTEGER); INSERT INTO employees (emp_id, dept_id, salary) VALUES (1, 101, 50000), (2, 101, 60000), (3, 102, 55000), (4, 102, 65000);
```sql
WITH RankedEmployees AS (
    SELECT emp_id, dept_id, salary,
           LAG(salary) OVER (PARTITION BY dept_id ORDER BY emp_id) AS prev_salary
    FROM employees
)
SELECT emp_id, dept_id, COALESCE(prev_salary, 0) AS prev_salary
FROM RankedEmployees
ORDER BY emp_id;
```
```sql
WITH RankedEmployees AS (
    SELECT emp_id, dept_id, salary,
           LAG(salary) OVER (PARTITION BY dept_id ORDER BY emp_id) AS prev_salary
    FROM employees
)
SELECT emp_id, dept_id, COALESCE(prev_salary, 0) AS prev_salary
FROM RankedEmployees
ORDER BY emp_id;
```