Juan Francisco Gancia
Juan Francisco Gancia

Reputation: 129

SQL query to find rows where a column value is equal to the sum of tow other columns in the same row

I need to build a SQL query to find rows from a table where a column value "total cost" is equal to the sum of two other columns "price", "discount" in the same row.

This is my query:

$sql = "SELECT * FROM pedido INNER JOIN clientes ON
pedido.clientes_id=clientes.clientes_id INNER JOIN chofer 
ON pedido.chofer_id=chofer.chofer_id WHERE clientes.clientes_nombre
LIKE '%$filtro_nombre%' AND pedido.pedido_fecha LIKE '%$filtro_fecha%' 
AND pedido.pedido_costo = SUM(pedido_descuento + pedido_saldo)
ORDER BY pedido_id DESC LIMIT 20 OFFSET $offset";

The query works removing the part of the SUM():

AND pedido.pedido_costo = SUM(pedido_descuento + pedido_saldo)

Example:

$sql = "SELECT * FROM pedido INNER JOIN clientes ON
pedido.clientes_id=clientes.clientes_id INNER JOIN chofer 
ON pedido.chofer_id=chofer.chofer_id WHERE clientes.clientes_nombre
LIKE '%$filtro_nombre%' AND pedido.pedido_fecha LIKE '%$filtro_fecha%'
ORDER BY pedido_id DESC LIMIT 20 OFFSET $offset";

I don't really know how to SUM two values in a SQL query.

Upvotes: 0

Views: 489

Answers (1)

jonju
jonju

Reputation: 2736

SUM is use to calculate the sum of a particular Column not Rows. Therefore the way you are using SUM won't work. For your requirement. Refer the query below

SELECT * 
FROM 
    pedido 
INNER JOIN 
    clientes ON pedido.clientes_id=clientes.clientes_id 
INNER JOIN 
    chofer ON pedido.chofer_id=chofer.chofer_id 
WHERE 
    clientes.clientes_nombre LIKE '%$filtro_nombre%' 
AND 
    pedido.pedido_fecha LIKE '%$filtro_fecha%' 
AND 
    pedido.pedido_costo = (pedido_descuento + pedido_saldo)
ORDER BY pedido_id 
DESC LIMIT 20 OFFSET $offset";

Upvotes: 3

Related Questions