2

enter image description here enter image description here

i have tried with below code. but i didnt get ouput as per multiple column.

select Name=stuff((select ','+ 
 name from Input t1 WHERE t1.Name=t2.name for xml path('')),1,9,''),NAME 
 =stuff((select ','+ 
 name from Input t1 WHERE t1.Name=t2.name for xml path('')),1,1,'')FROM 
 Input T2
 GROUP BY NAME

5 Answers 5

3

I have separated the character and numeric parts of the given string in CTE and used a simple group by and sum clause on that.

;With CTE
As
(
    Select 
        Left(Names, 1) As String,
        SUBSTRING(Names, 2, Len(Names) - 1) As Number
    From SeparateColumns
)
Select 
    String,
    Sum(Cast(Number As Int)) As SumOfDigits
From CTE
Group By String
Order By String;
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I know, what a coincidence. Jinx :)
1

Assuming you will have single character in your column, the following code works

CREATE TABLE #TEMP_SPLIT
(VALUE VARCHAR(25))


INSERT INTO #TEMP_SPLIT
SELECT 'A10'
UNION
SELECT 'B20'
UNION
SELECT 'A30'
UNION
SELECT 'B40'
UNION
SELECT 'A10'
UNION
SELECT 'C1'


SELECT c, sum(tot) 
FROM
     (
        SELECT SUBSTRING(VALUE,1,1) c ,CONVERT(FLOAT,SUBSTRING(VALUE,2,LEN  (VALUE)-1)) Tot
         FROM #TEMP_SPLIT

      )T     
 GROUP BY C

 DROP TABLE #TEMP_SPLIT

Comments

1

If the names column is always in the specified format, then use LEFT function to extract the character part and RIGHT function to extract the digits part and use these two in the sub-query and use GROUP BY clause and SUM function.

Query

select t.col_a as [string character], 
sum(cast(t.col_b as int)) as [sum of digits] from(
    select left(names, 1) as col_a,
    right(names, len(names) - 1) as col_b
    from [your_table_name]
) t
group by t.col_a;

Find a example here

Comments

1

You could use PATINDEX() with SUBSTRING() function if names always in this specified format

select A.CHAR [Strings], SUM(CAST(A.VALUE AS INT)) [Sum] from 
(
    SELECT SUBSTRING(Name, 1, PATINDEX('%[^A-Z]%', Name)-1) [CHAR], SUBSTRING(Name, PATINDEX('%[0-9]%', Name), len(Name)) [VALUE] FROM <table>
) a GROUP BY A.CHAR

Comments

1

Here's simple solution using subquery and group by clause:

select [StringChar], SUM([Number]) from (
    select SUBSTRING(Names, 1, 1) as [StringChar],
           convert(int, SUBSTRING(Names, 2, LEN(Names))) as [Number]
    from [Input]
) as a group by [StringChar]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.