I can think of a solution in the following way:
- a
cantidad
field that could be in the ventas
table or another. That will depend on the structure of your database. Here I have put it in the same table ventas
to simplify.
- you apply the
SUM
function on that field to calculate the quantity of products sold.
- you use
GROUP BY
so that the sum is made taking into account two criteria: id_pro
and fecha_venta
, so that you add the sales of each product by specific date.
- you finally use
HAVING
to evaluate that amount is less than 20,000
I leave this example, if you want to apply more filters as WHERE fecha_venta = '....'
add more columns in the SELECT, put the field cantidad
in another table, etc, you can do without problems. That will depend on your needs. The goal is to see how it works, analyzing the Query 1 .
You will see in the INSERT
that I have put two rice sales of 10,000 each on May 1, and you will see that the rice product does not come out in the query that day. :)
EDIT INCLUDING PRODUCTS NOT SOLD
DEMO SQL Fiddle
MySQL 5.6 Schema Setup :
DROP TABLE IF EXISTS producto;
CREATE TABLE producto
( id_pro int(11) NOT NULL AUTO_INCREMENT,
nombre_pro varchar(250) DEFAULT NULL,
imagen_pro varchar(250) DEFAULT NULL,
status_pro varchar(10) DEFAULT NULL, PRIMARY KEY (id_pro)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO producto (id_pro,nombre_pro)
VALUES
(1,"Arroz"),
(2,"Carne"),
(3,"No vendido")
;
DROP TABLE IF EXISTS ventas;
CREATE TABLE ventas
( id_ventas int(11) NOT NULL AUTO_INCREMENT,
id_producto int(11) DEFAULT NULL,
fecha_venta date DEFAULT NULL,
monto_venta decimal(19,2) DEFAULT NULL,
cantidad int DEFAULT NULL,
PRIMARY KEY (id_ventas)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO
ventas (id_ventas, id_producto, fecha_venta, monto_venta, cantidad)
VALUES
(1,1,'2017-05-01',1000.00,10000),
(2,1,'2017-05-01',1000.00,10000),
(3,1,'2017-05-02',700.00,7000),
(4,2,'2017-05-01',10.00,1),
(5,2,'2017-05-01',350.00,33),
(6,2,'2017-05-02',723.00,89);
Query 1 :
SELECT p.nombre_pro, v.fecha_venta, SUM(v.cantidad) AS total FROM
producto p
LEFT JOIN ventas v
ON p.id_pro=v.id_producto
GROUP BY p.id_pro,v.fecha_venta
HAVING total < 20000 OR total IS NULL
Results :
| nombre_pro | fecha_venta | total |
|------------|-----------------------|--------|
| Arroz | May, 02 2017 00:00:00 | 7000 |
| Carne | May, 01 2017 00:00:00 | 34 |
| Carne | May, 02 2017 00:00:00 | 89 |
| No vendido | (null) | (null) |