sql - How would I use a CURSOR to iterate through a list of values to do a calculation for each value? -
i have searched , searched way i'm trying do, haven't found solution yet. have dates stored in table so:
dates code sum 1-15-2015 aaa (to calculated) 2-2-2016 bbb (to calculated) 11-23-2015 ccc (to calculated)
the sum
each record in table calculated based on date in date
column. want use date date
column parameter of sorts calculation each record in table. assume cursor best approach, new sql , don't how implement such functionality. example's sake, can totally make sum calculation. it's trivial, anyway. have looked @ several examples elsewhere, i've had no luck. appreciated.
the sum calculation
the sum calculated pulling values out of database, via pass-through query, within date range. date range determined date in dates
column of example table. date range date value in dates
column today's date (getdate()
). need know how change left date date in dates
column each record in sample table. efficiency key.
my answer generic, you'll need either outer apply
or cross apply
depending on if want filter null
values or not.
the syntax similar this:
select a.dates, a.code, x.sum yourtable outer apply ( select sum(b.stufftosum) sum otherdatabase.otherschema.othertable b b.date between a.dates , getdate() ) x
your outer apply
logic should match actual logic you're using, i'm using example showing how can date range date in first table getdate()
.
using outer apply
, if there no values in other table fall in date range, return null
. in case of cross apply
, entire record filtered out (this behaviour similar of inner
, outer joins
).
Comments
Post a Comment