SELECT
	rs.id,
	NULL as accept_order_id,
	1 as rev_number,
	rs.input_date as input_date,
	rs.restoration_date as target_date,
	35 as user_id,
	19 as section_id,
	2 as restoration_trigger_code,
	CASE rd.restoration_type_id WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 3 ELSE 1 END as restoration_type_code,
	660 as own_warehouse_id,
	rs.hospital_id as warehouse_id,
	st.user_position_id as user_position_id,
	up.user_id as sales_user_id,
	la.sales_area_id as sales_area_id,
	up.section_id as sales_section_id,
	rs.dealer_id as customer_id,
	1 as supplier_id,
	rs.close_flag_id as state_code,
	rs.restoration_note as note,
	0 as invalid_flag_code,
	rs.print_sheet as print_sheet_date,
	NULL as deleted_at,
	NOW() as created_at,
	NOW() as updated_at
FROM
	(SELECT
		restoration_id,
		restoration_type_id
	FROM restoration_details
	GROUP BY restoration_id
	) as rd
LEFT JOIN restorations as rs
	ON rd.restoration_id = rs.id
LEFT JOIN staffs as st
	ON rs.staff_id = st.id
LEFT JOIN user_positions as up
	ON st.user_position_id = up.id
LEFT JOIN local_areas as la
	ON rs.local_area_id = la.id
INTO OUTFILE "/tmp/restorations.csv" FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"';