繁体   English   中英

SQL Server-单个单元的拆分和求和

[英]SQL server - Split and sum of a single cell

我有一个类型为nvarchar(max)的表单元格,通常看起来像这样:A03 B32 Y660 P02

例如,字母后跟数字,以空格分隔。 我要做的是在SQL过程中获得所有这些数字的和。 在其他语言中,这很简单,但是我对SQL还是相当陌生,此外,在我看来,它还像是一种笨拙的语言,无法使用字符串。 Aaanyway,我想它会像这样:

1)创建一个临时表并使用拆分功能填充它

2)删除每个单元格的第一个字符

3)将数据转换为int

4)将目标表。列设置为所述临时表的总和。

所以我做到了这一点:

CREATE PROCEDURE [dbo].[SumCell] @delimited nvarchar(max), @row int
AS
BEGIN
declare @t table(data nvarchar(max))

declare @xml xml 
set @xml = N'<root><r>' + replace(@delimited,' ','</r><r>') + '</r></root>' 

insert into @t(data) 
select  
    r.value('.','varchar(5)') as item 
from @xml.nodes('//root/r') as records(r) 

UPDATE TargetTable
SET TargetCell = SUM(@t.data) WHERE id = @row
END

显然,缺少第一个字符剥离和转换为int部分,最重要的是,我收到“必须声明标量变量@t”错误...

问题不是很清楚,因此假设您的文本位于单个单元格(如A3 B32 Y660 P20)中,可以使用以下代码段获取和。

DECLARE @Cell NVARCHAR(400), @Sum INT, @CharIndex INT

SELECT @Cell = 'A3 B32 Y660 P20',@Sum=0

WHILE (LEN(LTRIM(@Cell))>0)
BEGIN
    SELECT @CharIndex =  CHARINDEX(' ',@Cell,0)

    SELECT @Sum = @Sum + 
       SUBSTRING(@Cell,2,CASE WHEN @CharIndex>2 THEN @CharIndex-2 ELSE LEN(@Cell)-1 END )

    SELECT @Cell = SUBSTRING(@Cell,@CharIndex+1,LEN(@Cell))

    IF NOT (@CharIndex >0) BREAK;
END
--@Sum has the total of cell numbers
SELECT @Sum 

我假设您确实希望能够在定界列表中找到一个表的全部选择值的总和。 因此,我认为您问题中最复杂的部分是分割价值。 我倾向于使用的方法需要一个数字表,所以我将从此开始:

--If you really want to use a temporary numbers table don't use this method!
create table #numbers(
  Number int identity(1,1) primary key
)
declare @counter int
set @counter = 1
while @counter<=10000
 begin
    insert into #numbers default values
    set @counter = @counter + 1
 end

我还将创建一些测试数据

create table #data(
  id int identity(1,1),
  cell nvarchar(max)
)
insert into #data(cell) values('A03 B32 Y660 P02')
insert into #data(cell) values('Y72 A12 P220 B42')

然后,我将拆分功能放入CTE中以保持环境整洁:

;with split as (
    select d.id,
        [valOrder] = row_number() over(partition by d.cell order by n.Number),
        [fullVal] = substring(d.cell, n.Number, charindex(' ',d.cell+' ',n.Number) - n.Number),
        [char] = substring(d.cell, n.Number, 1),
        [numStr] = substring(d.cell, n.Number+1, charindex(' ',d.cell+' ',n.Number) - n.Number)
    from #data d
        join #numbers n on substring(' '+d.cell, n.Number, 1) = ' '
    where n.Number <= len(d.cell)+1
)
select id, sum(cast(numStr as int))
from split
group by id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM