I came up with this code:
selectPntKey,
RowNumber,
CASE
WHEN RowNumber = 1 THEN Qty
ELSE 0
ENDQty,
min(FromDate1),
max(ToDate1),
min(FromDate2),
max(ToDate2)
from
(
selectPntKey,
ROW_NUMBER() OVER(PARTITION BY PntKey ORDER BY PntKey) AS 'RowNumber',
Parent.PntQty Qty,
Child1.Cd1FromDate FromDate1,
Child1.Cd1ToDate ToDate1,
null FromDate2,
null ToDate2
FROM Parent
LEFT JOIN Child1 ON Child1.Cd1PntKey = Parent.PntKey
union
select PntKey,
ROW_NUMBER() OVER(PARTITION BY PntKey ORDER BY PntKey) AS 'RowNumber',
Parent.PntQty Qty,
null FromDate1,
null ToDate1,
Child2.Cd2FromDate FromDate2,
Child2.Cd2ToDate ToDate2
FROM Parent
LEFT JOIN Child2 ON Child2.Cd2PntKey = Parent.PntKey
) as work
group by PntKey,
RowNumber,
CASE
WHEN RowNumber = 1 THEN Qty
ELSE 0
END
And I get results like this:
PntKey RowNumber Qty FromDate1 ToDate1 FromDate2 ToDate2
----------- -------------------- ----------- ---------- ---------- ---------- ----------
1 1 100 2012-01-01 2012-02-01 2011-12-01 2011-12-31
1 2 0 2012-04-01 2012-05-01 NULL NULL
2 1 200 2012-01-15 2012-05-15 2012-01-01 2012-02-01
2 2 0 NULL NULL 2012-02-15 2012-05-15
3 1 300 2012-05-01 2012-07-01 2012-09-01 2012-10-01
Warning: Null value is eliminated by an aggregate or other SET operation.
(5 row(s) affected)