简体   繁体   中英

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?

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.

You can use the SUM aggregate function with a GROUP BY clause like so:

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):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM