Reputation: 7270
I have the following string to make it as expected.
Given String:
DECLARE @String VARCHAR(MAX) = '[ColumnA],[ColumnB],[ColumnC]'
/*Will be any numbers of columns*/
Expected String:
SUM([ColumnA]) AS [ColumnA],SUM([ColumnB]) AS [ColumnA],SUM([ColumnC]) AS [ColumnA]
SELECT 'SUM('+ REPLACE(@String,',','),SUM(') + ')'
I am just able to get:
SUM([ColumnA]),SUM([ColumnB]),SUM([ColumnC])
Got stuck to assign the alias infront of each sum.
Upvotes: 2
Views: 35
Reputation: 3866
I'd used one of split functions and FOR XML
.
SELECT STUFF(
(select ', SUM('+sit.items +') AS '+sit.items
from dbo.uf_SplitIntoTableStr('[column1],[column2]',',') sit
for xml path('')
),1,1,'')
Upvotes: 1