sql server - How to get 'sum' less than one value in sql -


test statement :

create table #t (   isid int primary key identity(1,1),   amount decimal(18,2) ) go  insert #t values(23.43) insert #t values(213.43) insert #t values(523.3) insert #t values(23.4) insert #t values(263.23) insert #t values(223.43)  drop table #t 

how 'sum' less 1 value(ex.500) order isid? there has 1 statement

select * #t exists(select 1 #t isid<=a.isid having sum(amount)<500) 

but has bug. when first value more 500 , second value negative number.

ex:

insert #t values(503.43) insert #t values(-13.43) 

the result has 1 value(-13.43).

to accomplish this, think can generate running totals values in our set , pick maximum "isid" has sum less 500.

    create table t     (       isid int primary key identity(1,1),       amount decimal(18,2)     )     go      insert t values(503.43)     insert t values(-13.43)     insert t values(5.00)     insert t values(1.00)     insert t values(55.00)  select isid t isid <=  (   select max(b.isid)       (       select       t1.isid,       t1.amount,       sum(t2.amount) summedamount       t t1       inner join t t2 on t2.isid <= t1.isid       group t1.isid, t1.amount       having sum(t2.amount) < 500     ) b ) 

here sqlfiddle: http://www.sqlfiddle.com/#!3/968af/4


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -