按顺序同字段求和问题,求助
字段1 字段2 字段3A 2 3
A 3 3
B 2 2
B 3 5
A 2 2
B 3 1
得到以下结果:
字段1 字段2 字段3
A 5 6
B 3 7
A 2 2
B 3 1
DECLARE @t TABLE( id INT, 字段1 VARCHAR(10), 字段2 INT, 字段3 INT ) INSERT @t VALUES ( 1, 'A', 2, 3 ), ( 6, 'A', 3, 3 ), ( 8, 'B', 2, 2 ), ( 12, 'B', 3, 5 ), ( 25, 'A', 2, 2 ), ( 56, 'B', 3, 1 ) SELECT * FROM @t AS T DECLARE @th TABLE( Groupkey VARCHAR(20), id INT, 字段1 VARCHAR(10), 字段2 INT, 字段3 INT ) INSERT @th SELECT CONCAT( ROW_NUMBER() OVER ( ORDER BY T.id ) - ROW_NUMBER() OVER ( PARTITION BY T.字段1 ORDER BY T.id ), '|', T.字段1), * FROM @t AS T ORDER BY T.id --SELECT * FROM @th AS T SELECT MIN(id) id, T.字段1, SUM(T.字段2) 字段2, SUM(T.字段3) 字段3 FROM @th AS T GROUP BY T.Groupkey, T.字段1 ORDER BY id