简体   繁体   中英

SQL Server 2012 Reset sum when value is null

Col 1   Value 
--------------
val1    5
val2    45
val3    6
val4    NULL
val5    NULL
val6    65
val7    25
val8    NULL
val9    545
val10   NULL
val11   NULL
val12   NULL

I have this table and I must sum the values from column Value , but when Value is null, I must reset the sum and start from 0. So the first sum must be 56 then 90 then 545. How can I do that? Thanks

The expected result is a table with 3 rows with following values 56,90,545

SQL DEMO

with cte as (
    SELECT *,
           COUNT(CASE WHEN [Value] IS NULL THEN 1 END) 
               OVER (order by [Col 1]) as grp
    FROM Table1       
) 
SELECT SUM(value)
FROM cte
GROUP BY grp
HAVING SUM(value) IS NOT NULL

OUTPUT

在此处输入图片说明

NOTE: I have to fix your data so can order using the value of [Col 1] . 1 to 01 . Otherwise you need provide a field to order the data because data set doesn't have an intrinsic order.

As a alternative with @Juan Carlos Oropeza option, you can do this.

Keeping the Column Name the same with the VAL1, VAL2 etc... Replace:

 OVER (order by [Col 1]) as grp

WITH:

OVER (order by CONVERT(INT,SUBSTRING([Col 1],4,10))) as grp

You can try this query. It will create group base on NULL on value column.

Updated: If your [Col 1] is dummy data and there are no columns for us to sort the data. This query can not guarantee.

declare @temp table(col1 varchar(50), value int)

insert into @temp values('val1',5)
insert into @temp values('val2',45)
insert into @temp values('val3',6)
insert into @temp values('val4',null)
insert into @temp values('val5',null)
insert into @temp values('val6',65)
insert into @temp values('val7',25)
insert into @temp values('val8',null)
insert into @temp values('val9',545)
insert into @temp values('val10',null)
insert into @temp values('val11',null)
insert into @temp values('val12',null)

select value, 0 as groupNo
into #temp 
from @temp

declare @group int = 1

update t
set @group = case when value is not null then @group else @group + 1 end
    ,groupNo = @group
from #temp as t

select sum(value) as SumValue
from #temp
where value is not null
group by groupNo
drop table #temp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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