你可以试试这个:
DECLARE @tbl TABLE (id VARCHAR(10), date DATE, amt INT)
INSERT @tbl VALUES
('001', CONVERT(DATE, '01/01/2012', 103), 100),
('001', CONVERT(DATE, '01/12/2011', 103), 200),
('002', CONVERT(DATE, '01/01/2013', 103), 100),
('002', CONVERT(DATE, '01/12/2012', 103), 200),
('003', CONVERT(DATE, '12/08/2012', 103), 500),
('003', CONVERT(DATE, '31/12/2011', 103), 200),
-- Added to display the one id - one row situation
('004', CONVERT(DATE, '14/02/2011', 103), 999),
('000', CONVERT(DATE, '02/02/2012', 103), 100),
('100', CONVERT(DATE, '09/09/2011', 103), 999)
;WITH a AS
(
SELECT id
, amt
, date
, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date ASC) num
, COUNT(*) OVER (PARTITION BY id) cnt
FROM @tbl
)
SELECT t1.id
, t1.date
, ABS(t1.amt - t2.amt)
FROM a t1
JOIN a t2 ON (t1.id = t2.id AND t1.num = t2.num + 1)
OR (t1.id = t2.id AND t2.cnt = 1)
id 1 和 2 的第一行和第二行之差为 -100,因此我添加了ABS
返回绝对值的函数。
我还添加了示例数据,以显示每个 id 只有一条记录时如何处理这种情况。