-- Ventas mensuales por linea por cliente
-- Incluye familia, sector, y linea de analisis de Directorio
-- Excluye traslados
-- Cambios solicitados en 2013-06-25: Zona y Suc2

SELECT
	IF(
		dv.id_vendedor IN ('ASJ','RDC','RDCA','EZS','JRM'),
		'bog_estr',
		dv.id_sucursal
	) AS Branch_for_analysis,
	dv.id_sucursal AS Branch,
	IF(
		dv.id_sucursal IN ('arm','per'),
		'eje_cafetero',
		IF(
		dv.id_sucursal IN ('bar','san'),
			'bar_san',
			dv.id_sucursal
		)
	) AS Zone,
	se.id_sector AS Id_Sector,
	se.descripcion AS Sector,
	sbse.descripcion AS Subsector,
	cs.id_cliente AS Id_Client,
	cs.nombre_cliente AS Client,
	dv.id_vendedor AS Id_Salesrep,
	vdr.nombre_vendedor AS Salesrep,
	YEAR(dv.fecha) AS Year,
	MONTH(dv.fecha) + ((YEAR(dv.fecha)-2011)*12) AS Month_seq,
	l.familia AS 'Type',
	ls.subfamilia AS Subtype,
	l.id_linea_analisis AS Id_Line1,
	l.linea_analisis AS Line1,
	l.id_linea AS Id_Line2,
	l.descripcion AS Line2,
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Sales_Kg,
	SUM(dvi.valor) AS Sales_COP,
	SUM(dvi.valor-dvi.costo) AS Gross_Margin,
	ROUND(
		SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
	) AS Sales_MT

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi
		ON ( dv.id_documento=dvi.id_documento 
			AND dv.id_sucursal=dvi.id_sucursal )
	JOIN item i
		ON ( dvi.id_item=i.id_item 
			AND dvi.id_sucursal=i.id_sucursal )
	JOIN cliente_has_sucursal cs
		ON ( dv.id_sucursal=cs.id_sucursal 
			AND dv.id_cliente=cs.id_cliente )
        LEFT JOIN view_lineas l
		ON ( LEFT(i.id_linea,2) = l.id_linea )
	LEFT JOIN linea_has_subfamilia ls
		ON ( l.id_linea = ls.id_linea)
	LEFT JOIN solosector se
		ON ( LEFT(cs.id_sector,2) = se.id_sector )
	LEFT JOIN subsector sbse
		ON ( cs.id_sector = sbse.id_sector )
	LEFT JOIN vendedor vdr
		ON ( dv.id_vendedor = vdr.id_vendedor
			AND dv.id_sucursal = vdr.id_sucursal)

WHERE
    LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MBPC]" 
    AND (i.tipo != "5")
    AND (dv.id_cliente != "999")
    AND YEAR(dv.fecha) = 2012

GROUP BY
	Month_seq,Branch,Id_Client,Month_seq,Id_Line1,Id_Line2,Id_Salesrep

ORDER BY
	Month_seq,Branch,Id_Client,Month_seq,Id_Line1,Id_Line2,Id_Salesrep
