SELECT
	sh.id as id,
	NULL as accept_order_id,
	NULL as shipping_order_id,
	1 as rev_number,
	sh.input_date as input_date,
	sh.shipping_date as target_date,
	35 as user_id,
	19 as section_id,
	2 as shipping_trigger_code,
	1 as supplier_id,
	660 as own_warehouse_id,
	sh.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,
	sh.dealer_id as customer_id,
	sh.delivery_id as shipment_customer_id,
	NULL as delivery_id,
	sh.trucking_id as trucking_id,
	sh.receiver_name as receiver_name,
	sh.request_time as request_time,
	1 as shipping_sheet_type_code,
	CASE sh.shipping_status_id WHEN 1 THEN 0 WHEN 3 THEN 1 WHEN 2 THEN 2 ELSE NULL END as shipping_state_code,
	CASE sd.shipping_type_id WHEN 1 THEN 5 WHEN 2 THEN 1 WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 8 WHEN 6 THEN 4 WHEN 7 THEN 6 WHEN 8 THEN 7 WHEN 9 THEN 9 WHEN 10 THEN 9 WHEN 11 THEN 9 WHEN 12 THEN 4 ELSE NULL END as shipping_type_code,
	sh.shipping_message as note,
	sh.shipping_note as shipping_note,
	sh.print_flag as print_picking_date,
	sh.print_sheet as print_sheet_date,
	0 as invalid_flag_code,
	NULL as deleted_at,
	NOW() as created_at,
	NOW() as updated_at
FROM
	(SELECT
		shipping_id,
		shipping_type_id
	FROM shipping_details
	GROUP BY shipping_id
	) as sd
LEFT JOIN shippings as sh
	ON sd.shipping_id = sh.id
LEFT JOIN staffs as st
	ON sh.staff_id = st.id
LEFT JOIN user_positions as up
	ON st.user_position_id = up.id
LEFT JOIN local_areas as la
	ON sh.local_area_id = la.id
INTO OUTFILE "/tmp/shippings.csv" FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"';