注册 登录
编程论坛 SQL Server论坛

按顺序同字段求和问题,求助

king_9 发布于 2021-01-09 16:13, 4737 次点击
字段1   字段2    字段3
A        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
3 回复
#2
blue12021-01-20 10:14
#3
sssooosss2021-02-19 08:39
共同学习
#4
oldfish962021-04-25 14:07
程序代码:
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


只有本站会员才能查看附件,请 登录
1