SELECT a.cod_prod, b.cantida AS cant_compra, b.ptotal AS tota_compra, c.cantida AS cant_venta,c.ptotal AS total_venta FROM existencias a LEFT JOIN (SELECT cod_prod, SUM (cantida) AS cantida, SUM (ptotal) AS ptotal FROM compra_dt GROUP BY cod_prod) b ON a.cod_prod = b.cod_prod LEFT JOIN (SELECT cod_prod, SUM (cantida) AS cantida, SUM (ptotal) AS ptotal FROM venta_dt GROUP BY cod_prod) c ON a.cod_prod = c.cod_prodGROUP BY a.cod_prod
CREATE TABLE compra_cb ( nfactura varchar(25) PRIMARY KEY, fecha date, cod_prov varchar(25), total varchar(15));CREATE TABLE compra_dt ( nfactura nvarchar(25), cod_prod varchar(25), cantida float, punitario float, ptotal varchar(13), costopromedio float, totalexistencia varchar(13));CREATE TABLE venta_cb ( nfactura varchar(25) PRIMARY KEY NOT NULL, venta integer, baja integer, fecha date, cliente varchar(80), total varchar(15));CREATE TABLE venta_dt ( nfactura varchar(25), cod_prod varchar(25), cantida float(8,2), costopromedio float(8,2), ptotal varchar(13));
SELECT a.cod_prod, b.cantida AS cant_compra, b.ptotal AS tota_compra, c.cantida AS cant_venta,c.ptotal AS total_venta FROM existencias a LEFT JOIN (SELECT cod_prod, SUM (cantida) AS cantida, SUM (ptotal) AS ptotal FROM compra_dt GROUP BY cod_prod) b ON a.cod_prod = b.cod_prod LEFT JOIN (SELECT cod_prod, SUM (cantida) AS cantida, SUM (ptotal) AS ptotal FROM venta_dt GROUP BY cod_prod) c ON a.cod_prod = c.cod_prodINNER JOIN compra_cb ON compra_cb.nfactura = compra_dt.nfacturaINNER JOIN venta_cb ON venta_cb.nfactura = venta_dt.nfacturaWHERE compra_cb.fecha BETWEEN 01/06/2013 AND 30/06/2013GROUP BY a.cod_prod
SELECT cod_prod, SUM (cantida) AS cantida, SUM (ptotal) AS ptotal FROM compra_dt GROUP BY cod_prod
(SELECT cod_prod, SUM (cantida) AS cantida, SUM (ptotal) AS ptotal FROM venta_dt GROUP BY cod_prod