[英]Merging multiple rows with same column in SQL Server
What is the most efficient method to combine multiple rows of values with the same column in SQL Server?在 SQL 服务器中将多行值与同一列组合的最有效方法是什么?
data table数据表
category![]() |
segment![]() |
payment![]() |
---|---|---|
01 ![]() |
A![]() |
1425 ![]() |
01 ![]() |
B![]() |
7647 ![]() |
01 ![]() |
A![]() |
6164 ![]() |
01 ![]() |
B![]() |
3241 ![]() |
And I'm trying to achieve the following result我正在努力实现以下结果
category![]() |
segment![]() |
payment![]() |
---|---|---|
01 ![]() |
A![]() |
1425+6164 ![]() |
01 ![]() |
B![]() |
7647+3241 ![]() |
I want to merge the rows when the category and segment are same.当类别和段相同时,我想合并行。
Thanks in Advance!提前致谢!
Use This用这个
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
if you get payment with + sign then use stuff like this.如果您使用 + 号付款,请使用这样的东西。
SELECT category,segment,SUM(payment) as payment
FROM TABLENAME
GROUP BY category,segment
if you want sum then remove stuff and use Sum(payment)
only.如果你想要总和然后删除东西并只使用
Sum(payment)
。
You can use the SUM aggregate function with a GROUP BY clause like so:您可以将 SUM 聚合 function 与 GROUP BY 子句一起使用,如下所示:
SELECT category, segment, SUM(payment) AS 'payment'
FROM table
GROUP BY category, segment
if you want actual total, then you can aggregate and summarize:如果您想要实际总数,则可以汇总和汇总:
select category, segment, sum(payment)
from table
group by category, segment
if you want string, you can try something like that (for mysql):如果你想要字符串,你可以尝试这样的事情(对于 mysql):
select category, segment, GROUP_CONCAT(payment SEPARATOR '+')
from table
group by category, segment
your 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);
if you want payment column as string then use following如果您希望将付款列作为字符串,请使用以下内容
SELECT
category,
segment,
STRING_AGG(cast(payment as nvarchar(50)),'+')
WITHIN GROUP (ORDER BY category) payment
FROM
@t T
GROUP BY
category,segment
if you want payment column as NUMBER then use following如果您希望付款栏为 NUMBER,请使用以下
SELECT
category,
segment,
SUM(payment) AS payment
FROM
@t T
GROUP BY
category,segment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.