-- Ventas por documento con cliente, ciudad y sucursal

SELECT
	z.id_zona, z.descripcion, SUM(dvi.valor) AS valor, SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0,1,-1))) AS peso, SUM(dvi.valor-dvi.costo) 

    dv.id_sucursal AS Suc,
    cs.id_cliente AS Nit,
    cs.nombre_cliente AS Cliente,
    dv.id_documento AS Documento,
    LEFT(dv.id_documento,2) AS TipoDocumento,
    IF(LEFT(dv.id_documento,1)="F","Factura",IF(LEFT(dv.id_documento,1)="D","Devolucion",IF(LEFT(dv.id_documento,1)="T","Traslado","Desconocido"))) AS ClaseDocumento,
	    SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0,1,-1))) AS Peso,
	    SUM(dvi.valor) AS Valor,
	    SUM(dvi.valor-dvi.costo) AS Utilidad

	ciu.nombre_ciudad AS Ciudad,
	ciu.nombre_depto AS Departamento

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 ) JOIN zona z ON ( z.id_zona=LEFT(cs.id_zona,8) ) 


	JOIN view_ciudades ciu
	ON (ciu.id_ciudad = cli.id_zona)

WHERE LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MPB]" AND NOT (i.tipo LIKE "5") AND NOT (dv.id_cliente LIKE "999") AND dv.fecha = '2012-09-14' AND YEAR(dv.fecha)=YEAR('2012-09-14') 

GROUP BY z.id_zona 

ORDER BY valor DESC 
