SET NAMES 'utf8';

SELECT
	dv.id_sucursal AS Suc,
	cli.id_cliente AS Nit,
	cli.nombre_cliente AS Cliente,
	vdr.id_vendedor AS CodVendedor,
	vdr.nombre_vendedor AS Vendedor,
	dv.fecha AS Fecha,
	dv.id_documento AS Documento,
	i.id_item AS CodItem,
	i.descripcion AS Item,
	l.descripcion AS Linea,
	ROUND(SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1))), 2) AS Peso_Kg,
	SUM(dvi.valor) AS Valor

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 )
	LEFT JOIN cliente cli
		ON ( dv.id_cliente = cli.id_cliente )
	LEFT JOIN view_lineas l
		ON ( i.id_linea = l.id_linea )
	LEFT JOIN vendedor vdr
		ON ( dv.id_vendedor = vdr.id_vendedor)

WHERE
	dv.fecha >= "2021-07-01"
	AND dv.fecha <= "2021-12-31"
	AND vdr.id_vendedor = "66847518"

GROUP BY
	Suc,Nit,Documento,CodVendedor,CodItem

ORDER BY
	Suc,Nit,Documento,CodVendedor,CodItem
