Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table i.e.

create table tbl (id int, col1 varchar(50), col2 varchar(50),col3 varchar(50))insert into tbl values (1,'20','25','50')
insert into tbl values (2,'30','35','60')
insert into tbl values (3,'AB','AB','50')


I want to sum of three columns, for this I am using
select id, sum(convert(decimal,col1)+convert(decimal,col2)+convert(decimal,col3)) as total from tbl  group by id, col1, col2, col3 


Now I want to ignore varchar values and see result like

id    total
     1     95
     2     125
     3     50


Please help someone...

What I have tried:

select id, sum(convert(decimal,col1)+convert(decimal,col2)+convert(decimal,col3)) as total from tbl  group by id, col1, col2, col3 
Posted
Updated 27-Sep-17 23:16pm

1 solution

try

select id, (col1+col2+col3) as Total
 from  (
		select
		id, 
		case  ISNUMERIC(col1) when 1  then CAST(col1 as decimal) else 0 end as col1 ,
		case  ISNUMERIC(col2) when 1  then CAST(col2 as decimal) else 0 end as col2 ,
		case  ISNUMERIC(col3) when 1  then CAST(col3 as decimal) else 0 end as col3 
		from tbl  group by id, col1, col2, col3  
      )a 


Note: Please consider the points by Richard [^] in the comments section.
 
Share this answer
 
v6
Comments
Member 12245539 28-Sep-17 4:47am    
5 star
Karthik_Mahalingam 28-Sep-17 5:10am    
Thank you
Member 12245539 3-Oct-17 12:08pm    
Boss
I you don't mind then may I ask a little bit??

I want to show col1, col2 & col3 also like
ID COL1 COL2 COL3 TOTAL
1 20 25 50 95
2 30 35 60 125
3 AB AB 50 50
Karthik_Mahalingam 3-Oct-17 23:10pm    
select id,col1,col2,col3, (col1_s+col2_s+col3_s) as Total
 from  (
		select
		id, 
		col1,col2,col3,
		case  ISNUMERIC(col1) when 1  then CAST(col1 as decimal) else 0 end as col1_s ,
		case  ISNUMERIC(col2) when 1  then CAST(col2 as decimal) else 0 end as col2_s ,
		case  ISNUMERIC(col3) when 1  then CAST(col3 as decimal) else 0 end as col3_s 
		from tbl  group by id,col1,col2,col3   
      )a 
Member 12245539 5-Oct-17 2:18am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900