Flatten rows in SQL Server
Question
I need to flatten or collapse the rows from either tables before I can join both tables and perform calculation
TABLE - A
StartDate EndDate ValueA
2/1/2012 2/1/2012 1
2/2/2012 2/2/2012 2
2/3/2012 2/3/2012 3
2/7/2012 2/8/2012 4
TABLE - B
startdate enddate ValueB
2/1/2012 2/1/2012 4
2/2/2012 2/3/2012 5
2/7/2012 2/7/2012 6
2/8/2012 2/8/2012 7**
RESULT
StartDate EndDate ValueA ValueB
2/1/2012 2/1/2012 calc calc
2/2/2012 2/3/2012 calc calc
2/7/2012 2/8/2012 calc calc
for a record in table A: if there are multiple records in table B which are within the start and EndDAte of table A, then I need to "flatten" or "collapse" those records in table B before I can join to Table A to perform my calculations
Similarly, the same condition can exist the other way, such that table A has multiple records, that fall within Start and EndDate of table B, so in this case I need to flatten those records in table A so that it conforms to Start and End Date of table B.
I am able to acheive this using multiple cursors but the performance is pathetic, and I am hoping that someone would be able to provide a better solution to this problem
I hope my question is making sense to you guys
Thanks in advance
Solution
Give this one a shot (prob. not the most efficient... as I was in a hurry):
drop table tablea
drop table tableb
CREATE TABLE TableA (startdate DATE, enddate DATE, value INT)
CREATE TABLE TableB (startdate DATE, enddate DATE, value INT)
INSERT TableA SELECT '2/1/2012', '2/1/2012', 1
INSERT TableA SELECT '2/2/2012', '2/2/2012', 2
INSERT TableA SELECT '2/3/2012', '2/3/2012', 3
INSERT TableA SELECT '2/7/2012', '2/8/2012', 4
INSERT TableB SELECT '2/1/2012', '2/1/2012', 4
INSERT TableB SELECT '2/2/2012', '2/3/2012', 5
INSERT TableB SELECT '2/7/2012', '2/7/2012', 6
INSERT TableB SELECT '2/8/2012', '2/8/2012', 7
;WITH tablea_cte AS (
SELECT
StartDate
, EndDate
FROM
TableA a
WHERE EXISTS (SELECT * FROM TableB b WHERE b.startdate >= a.startdate and b.enddate <= a.enddate)
),
tableb_cte as (
SELECT
StartDate
, EndDate
FROM
TableB b
WHERE EXISTS (SELECT * FROM TableA a WHERE a.startdate >= b.startdate and a.enddate <= b.enddate)
),
tableab_cte AS (
SELECT * FROM tableb_cte union select * FROM tablea_cte
),
sumab_cte as (
SELECT
ab.startdate
, ab.enddate
, calcA = (SELECT SUM (value) FROM TableA a where a.startdate >= ab.startdate and a.enddate <= ab.enddate)
, calcB = (SELECT SUM (value) FROM TableB b where b.startdate >= ab.startdate and b.enddate <= ab.enddate)
FROM
tableab_cte ab
)
select * from sumab_cte