Monday, 19 August 2013

SQL Update a DateRange table from a SUM query of another table

SQL Update a DateRange table from a SUM query of another table

Table DateRangeTab (Fromdate, Todate, TotalValue) has data such as:
2010-01-01, 2011-01-01, 0
2010-01-01, 2012-01-01, 0
etc (i.e lots of date ranges all with 0 in the TotalValue column)
I also have table ValueTab (DateofValue, Value) which has data such as:
2010-01-02, £25
2011-01-01, £45
2011-05-04, £65
etc (i.e. lots of different rows with dates and a value for each date)
I need to update DateRangeTab TotalValue column with SUM of Value from
ValueTab table where the DateofValue falls in the range FromDate - Todate.
I tried something like the following :
Update DateRangeTab set TotalValue = a.Value from ( select sum(value) as
Value from ValueTab VT join DateRangeTab DT on VT.DateofValue between
DT.startdate and DT.ToDate) a
But it puts same total in each row of the DateRangeTab. Hope someone can
help or direct me to another post with a related answer.
Thanks

No comments:

Post a Comment