在 SQL 服务器中合并具有相同列的多行

Merging multiple rows with same column in SQL Server

在 SQL 服务器中将多行值与同一列合并的最有效方法是什么?

数据table

category segment payment
01 A 1425
01 B 7647
01 A 6164
01 B 3241

我正在努力实现以下结果

category segment payment
01 A 1425+6164
01 B 7647+3241

我想在类别和段相同时合并行。

提前致谢!

使用这个

SELECT category,segment,payment = STUFF((
                                SELECT '+' + CONVERT(VARCHAR,payment)
                                FROM TABLENAME t
                                WHERE t.category = TABLENAME.category AND t.segment = TABLENAME.segment                               
                                FOR XML PATH('')
                                ), 1, 1, '')
FROM TABLENAME 
GROUP BY category,segment

如果您使用 + 号收款,请使用类似的方式。

SELECT category,segment,SUM(payment) as payment
FROM TABLENAME 
GROUP BY category,segment

如果你想要求和,那么删除东西并只使用 Sum(payment)

您可以像这样将 SUM 聚合函数与 GROUP BY 子句一起使用:

SELECT category, segment, SUM(payment) AS 'payment'
FROM table
GROUP BY category, segment

如果你想要实际总数,那么你可以汇总和总结:

select category, segment, sum(payment)
from table
group by category, segment

如果你想要字符串,你可以尝试类似的东西(mysql):

select category, segment, GROUP_CONCAT(payment SEPARATOR '+')
from table
group by category, segment

你的table

 declare @t TABLE (
   category int  NOT NULL 
  ,segment  NVARCHAR(50) NOT NULL
  ,payment  int  NOT NULL
);
INSERT INTO @t(category,segment,payment) VALUES (01,'A',1425);
INSERT INTO @t(category,segment,payment) VALUES (01,'B',7647);
INSERT INTO @t(category,segment,payment) VALUES (01,'A',6164);
INSERT INTO @t(category,segment,payment) VALUES (01,'B',3241);

如果您希望付款列为字符串,请使用以下内容

SELECT
category, 
segment,
    STRING_AGG(cast(payment as nvarchar(50)),'+') 
        WITHIN GROUP (ORDER BY category) payment
FROM
   @t T
GROUP BY
    category,segment

如果您希望付款列为 NUMBER,请使用以下内容

SELECT
category, 
segment,
SUM(payment) AS payment 
FROM
   @t T
GROUP BY
    category,segment