How to SUM odd and even digits ina big number with T-SQL


http://social.msdn.microsoft.com/Forums/en-US/958861e1-786b-4b51-8915-5ef33dc5657b/how-to-calculate-odd-and-even-place-digits-in-sql?forum=transactsql

 create table test (number varchar(50))
Insert into test values('196421744643'),('12121212121212')
select number,  SUM(Case WHEN num%2 =1 then Cast(substring(number,num,1) as int) end) OddSum,
SUM(Case WHEN num%2 =0 then Cast(substring(number,num,1) as int) end) EvenSum
 from test
 cross apply (Values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) d(num) 
 WHERE substring(number,num,1)<>''
 Group by number
 
 drop table test


 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s