By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
WITH yourTable AS (
SELECT 1 AS id, 'A' AS job_name, 10 AS duration UNION ALL
SELECT 2, 'B', 2 UNION ALL
SELECT 3, 'B', 3 UNION ALL
SELECT 4, 'C', 15 UNION ALL
SELECT 5, 'A', 12 UNION ALL
SELECT 6, 'D', 100 UNION ALL
SELECT 7, 'C', 9
),
cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY job_name ORDER BY id) rn
FROM yourTable
)
SELECT
job_name,
CASE WHEN MAX(rn) > 1 THEN
SUM(CASE rn WHEN 1 THEN duration WHEN 2 THEN -duration END) END AS duration_diff
FROM cte
GROUP BY
job_name;
job_name | duration_diff |
---|---|
A | -2 |
B | -1 |
C | 6 |
D | null |