Reputation: 129
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
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