Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 summarizing digits in a column

Author  Topic 

jose1024
Starting Member

5 Posts

Posted - 2004-08-17 : 14:04:50
I have a set of digits contained in a single column. How can I add all the digits in the column and post to a result column?
I have the following statement, but all it does is concatenate. Any ideas?

UPDATE CHECKDIGIT
SET ODDX3 = LEFT(CUSTID,1) + SUBSTRING(CUSTID,2,1)
go

Seventhnight
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2004-08-17 : 14:12:04
Does this help?


Declare @myTable table (col1 varchar(100), processed varchar(100), results int)

Insert Into @myTable values ('186475',null,0)
Insert Into @myTable values ('54224793',null,0)
Insert Into @myTable values ('35512347',null,0)
Insert Into @myTable values ('124',null,0)
Insert Into @myTable values ('722185',null,0)
Insert Into @myTable values ('3351118',null,0)

Select * From @myTable

While exists(Select 1 From @myTable Where len(Col1)>0)
Begin
Update @myTable
Set
col1 = Right(col1,len(col1)-1),
processed = isnull(processed,'') + left(col1,1),
results = results + convert(int,left(col1,1))
From @myTable
Where len(Col1)>0
End

Select * From @myTable


Corey
Go to Top of Page

Sitka
Aged Yak Warrior

571 Posts

Posted - 2004-08-17 : 14:12:09
[code]

CREATE TABLE CHECKDIGIT (CUSTID varchar(10), ODDX3 int)

INSERT INTO CHECKDIGIT VALUES (12,0)
INSERT INTO CHECKDIGIT VALUES (37,0)
INSERT INTO CHECKDIGIT VALUES (54,0)

SELECT CUSTID, ODDX3 from CHECKDIGIT


UPDATE CHECKDIGIT
SET ODDX3 = CAST(LEFT(CUSTID,1)as int) + CAST(SUBSTRING(CUSTID,2,1) as int)

SELECT CUSTID, ODDX3 from CHECKDIGIT

DROP TABLE CHECKDIGIT


[/code]

quote:
How can I add all the digits in the column



OOPS

Possessing a wide range of watered down skills.
Go to Top of Page

ehorn
Master Smack Fu Yak Hacker

1632 Posts

Posted - 2004-08-17 : 14:37:32
You can use a tally table to perform this
Tally table are very useful

Search for "tally" and you will see many uses for these
create table numbers ( n int primary key)
declare @n int
set @n = 0
while @n <=1000
begin
insert into numbers
select @n
set @n = @n+1
end
then using Sitkas DDL:
    
select custid, sum(convert(int,substring(custid,n,1))) sum_custid
from checkdigit c, numbers n
where n <= len(custid)
and n > 0
group by custid
Go to Top of Page
   

- Advertisement -