I need to generate a result set that will be coming from a table that includes parent and child rows. The result needs to be one row per parent and include the child row information (some aggregation like min for a date, sum of amounts). And, also include rows for the child data.
The table contains sales data and there are times when an order is changed and generates some related orders. The need is to have the original parent order on one row, that includes any information about the child orders and also one to N rows for the child orders with their details.
I have tried to use a CTE to get the self join, but i keep getting a cartesian product. I am wondering if i will need to build out separate temp tables for the query...one for the parent rows, one for the child rows?
Here is some t-sql to generate some sample data:
/** setting up table and inserting data **/
declare @mytable table (Status_Code varchar(100), Region varchar(100), Order_Amount float, OrderNum varchar(100), Orig_OrderNum varchar(100), OrderComplete datetime, OrderCreate datetime )
Insert into @mytable
Select 'Complete', 'Southeast', 15000.00, '55544400', '55544400', '2016-11-11', '2016-11-11'
Select 'Change_Complete', 'Southeast', 2500.00, '5556700', '55544400', '2016-12-09', '2016-12-09'
Select 'Change_Complete', 'Southeast', 1000.00, '5558890', '55544400', '2016-12-20', '2016-12-20'
Select 'Change_Complete', 'Southeast', 4400.00, '5567700', '55544400', '2017-01-14', '2017-01-14'
Select * from @mytable
The results need to look like this;
OrderNum Order_Complete Order_Amount Child Order Date (min) Child Order Amount Child_order_Date_new Child_Order_Amt_New Parent_Order_Num
55544400 2016-11-11 15000 2016-12-09 7900 null null null
5556700 null null null null 2016-12-09 2500 55544400
5558890 null null null null 2016-12-20 1000 55544400
5567700 null null null null 2017-01-14 4400 55544400