Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Rows in SQL Server 2008

I have a table like the one below:

Customer   |Type     |Count
Joe        |Silver-S |1
Joe        |Silver   |7
Joe        |Gold     |3
Joe        |Gold-S   |2

I need to merge this so that it looks like the following:

Customer   |Type     |Count
Joe        |Silver   |8
Joe        |Gold     |5

Help!

like image 688
AshesToAshes Avatar asked Mar 28 '26 21:03

AshesToAshes


2 Answers

select Customer, [Type], SUM([Count]) from (
    select Customer, replace([Type], '-S', '') [Type], [COUNT] from Customer
)
t
group by customer, [Type]
like image 124
Phil Avatar answered Mar 31 '26 05:03

Phil


Here is a solution utilising a partition approach:

SELECT DISTINCT Customer, REPLACE([Type], '-S', '') AS [Type], 
SUM([Count]) OVER (PARTITION BY (SELECT REPLACE([Type], '-S', ''))) AS [Count]
FROM Customer
like image 34
Aleksandr Fedorenko Avatar answered Mar 31 '26 04:03

Aleksandr Fedorenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!