-- Entradas de almacen por linea del mes

SELECT
	e.id_sucursal AS Sucursal,
	e.id_entrada AS Entrada,
	e.id_proveedor AS Nit_Proveedor,
	p.nombre_proveedor AS Nombre_Proveedor,
	e.fecha AS Fecha,
       	i.id_item AS Codigo_item,
       	i.descripcion AS Item,
       	l.descripcion AS Linea,
       	sl.descripcion AS Sublinea,
       	SUM(ei.costo * ei.cantidad) AS Costo, 
	SUM(ei.cantidad) AS Cantidad,
	SUM(ei.costo) AS Costo_unitario,
	ei.unidad AS Unidad_medida,
	de.factura AS Factura

FROM
	entrada e
	JOIN entrada_has_item ei
		ON ( e.id_entrada = ei.id_entrada
			AND e.id_sucursal = ei.id_sucursal )
	LEFT JOIN documentos_entrada de
		ON (de.id_entrada = e.id_entrada
			AND de.id_sucursal = e.id_sucursal )
	JOIN item i
		ON ( ei.id_item = i.id_item
			AND ei.id_sucursal = i.id_sucursal )
	JOIN view_lineas l
		ON ( l.id_linea = left( i.id_linea, 2 ) )
	JOIN linea sl
		ON ( sl.id_linea = i.id_linea 
			AND sl.tipo = i.tipo )
	JOIN proveedor p
		ON ( p.id_proveedor = e.id_proveedor )
	JOIN proveedor_has_sucursal ps
		ON ( p.id_proveedor = ps.id_proveedor
			AND ps.id_sucursal = e.id_sucursal )

WHERE
	p.id_proveedor > 999
	AND YEAR(e.fecha) = 2013

GROUP BY
	Entrada, Sucursal, Codigo_item

