I'm writing a query that creates an aggregate of a union of two tables, but I need the second table of the union to have some of the columns (sum)ed, and i'm not sure exactly the way to do this. This isn't part of a stored proc, so no variables. The details are below:
select t.col1, t.col2, t.col3 FROM (
select d.col1, d.col2, d.col3 FROM table1 d
join another_table
on ...
join different table
on ...
UNION ALL
select a.col1, a.col2, a.col3 FROM table2 a
join another_table
on ...
join different table
on ...
WHERE
/*datetime restricitons */
) t
So this is the problem: col3 in tables a and d are the same data, except in table b it is a total value, with each new row that is added being calculated based on the previous. (I have no control over these tables).
After the union, the 30 or so extra rows from table a gets added to the end of the rows from table d, the only problem is that table a isnt a cumulative value, its per row by itself.
Ideally, during the union, I would want to take the last row in table d's col3 value, and then the first row added from table a would be the val from table d's col3 +/- the value in col3 for table a.
I hope I explained this adequately, I know there is a way to do this, I'm just not sure how to apply it.
Here are examples of the two physical tables, and what the output aggregate looks like, and what it should look like:
table d:
table a:
output table: THE REDISH rows are from table d, while the BLUE are from table a.