我有一个这样的表:
ID Seq Amt 1 1 500 1 2 500 1 3 500 1 5 500 2 10 600 2 11 600 3 1 700 3 3 700
我想将连续序列号分组为一行,如下所示:
ID Start End TotalAmt 1 1 3 1500 1 5 5 500 2 10 11 1200 3 1 1 700 3 3 3 700
请帮助实现此结果。
WITH numbered AS ( SELECT ID, Seq, Amt, SeqGroup = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Seq) - Seq FROM atable ) SELECT ID, Start = MIN(Seq), [End] = MAX(Seq), TotalAmt = SUM(Amt) FROM numbered GROUP BY ID, SeqGroup ORDER BY ID, Start ;