简体   繁体   中英

Inner Join, Select SUM and Where

Hi!! I need to search for the stock.id where the SUM of all pedidos.cantidad is >= than $sale

I've wrote this, but seems like it's not working:

SELECT *
     , SUM(pedidos.cantidad) as total 
  FROM stock 
 INNER 
  JOIN pedidos 
    ON stock.producto = pedidos.producto 
 WHERE pedidos.producto = '$sale' 
   AND total >= stock.cantidad 
 ORDER 
    BY stock.id ASC 
 LIMIT 1

My Tables: stock

ID | Producto | Cantidad

Pedidos

ID | Producto | Lote | Cantidad

stock.producto needs to be = to pedidos.producto AND stock.id = pedidos.lote So I need this: SELECT stock.id WHERE (stock.cantidad -SUM(pedidos.cantidad)) >= $sale AND stock.producto = pedidos.producto AND stock.id = pedidos.lote

Exactly, When I'm registering a new sale, I need to find the stock.id where (stock.cantidad - SUM(pedidos.cantidad)) IS >= $new_sale to put that stock.id into the new input on pedidos.lote

Its kind of difficult for me trying to explain what I need because I speak Spanish, please apologize me for this

Without knowing your table and data structures.. give this a try:

SELECT Stock.ID
FROM   Stock
WHERE  Stock.Producto IN ( 
    SELECT  producto
    FROM    pedidos
    GROUP BY producto
    HAVING SUM(pedidos.cantidad) >= 100 // Your sale value
)

What this is doing is: Get all the Producto records that when grouped together have a sum > $sale then look for all the Stock.IDs which have the Producto's found.

EDIT

SELECT Stock.ID
FROM   Stock
WHERE  Stock.Producto IN ( 
    SELECT  Stock.ID, SUM(Pedidos.Cantidad)
    FROM    Pedidos
    INNER JOIN Stock ON Stock.ID = Pedidos.Lote
                     AND Stock.Producto = Pedidos.Producto
    GROUP BY Stock.ID, Pedidos.Producto
    HAVING  SUM(Pedidos.Cantidad) > 1000 --Sale Amount
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM