SELECT
	sa.id as id,
	1 as rev_number,
	NULL as accept_order_id,
	NULL as purchase_id,
	NULL as sale_id,
	sa.input_date as input_date,
	sa.sale_date as target_date,
	sa.op_date as operate_date,
	35 as user_id,
	19 as section_id,
	2 as sale_trigger_code,
	CASE sd.sale_type_id WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 4 WHEN 4 THEN 4 WHEN 5 THEN 2 ELSE NULL END as sale_type_code,
	sa.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,
	sa.dealer_id as customer_id,
	1 as supplier_id,
	sa.order_number as customer_order_number,
	sa.charge_id as charge_customer_id,
	sa.dealer_group_id as charge_customer_group_id,
	1 as sale_sheet_type_code,
	sa.total_price as total_price,
	sa.total_tax as total_duty,
	1 as duty_type_code,
	5 as duty_rate,
	0 as price_duty_type_code,
	1 as duty_calc_type_code,
	1 as frac_digit_code,
	1 as fraction_method_code,
	IF(sa.total_price<0,0,1) as sign_type_code,
	sa.cutoff_date as cutoff_date_code,
	sa.charge_timing_id as charge_timing_code,
	sa.close_flag_id as state_code,
	sa.sale_note as note,
	NULL as sale_note,
	0 as invalid_flag_code,
	sa.print_sheet as print_sheet_date,
	NULL as deleted_at,
	NOW() as created_at,
	NOW() as updated_at
FROM
	(SELECT
		sale_id,
		sale_type_id
	FROM sale_details
	GROUP BY sale_id
	) as sd
LEFT JOIN sales as sa
	ON sd.sale_id = sa.id
LEFT JOIN staffs as st
	ON sa.staff_id = st.id
LEFT JOIN user_positions as up
	ON st.user_position_id = up.id
LEFT JOIN local_areas as la
	ON sa.local_area_id = la.id
INTO OUTFILE "/tmp/sales.csv" FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"';