简体   繁体   中英

Merge multiple rows in column SQL SERVER without temporary table

I have following result set that i am creating by query.

ID | Name | CRAmount | DRAmount
1  | ABC  | 50000    | NULL
1  | ABC  | NULL     | 10000
1  | ABC  | 5000     | NULL
1  | ABC  | 6000     | NULL
1  | ABC  | NULL     | 7000

I want the result like

ID | Name | CRAmount | DRAmount
1  | ABC  | 61000    | 17000

I know i can do that by using temporary table but i want simple method to do. Thank you in advance.

You seem to want simple aggregation:

select id, name, sum(cramount) cramount, sum(dramount) dramount
from mytable
group by id, name

Try this

SELECT ID, Name, SUM(CRAmount) as CRAmount, SUM(DRAmount) as DRAmount
FROM TableName 
GROUP BY ID, Name;
GO  
SELECT ID , [Name] , SUM(ISNULL(CRAmount,0))CRAmount,SUM(ISNULL(DRAmount,0))DRAmount FROM #TEMP
GROUP BY ID , [Name]

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