Using MySQL
The query could be written using SUM()
.
This is an aggregation function that:
- Returns the sum of the indicated expression or column.
- If the set of returns has no rows,
SUM()
returns NULL
.
- The keyword
DISTINCT
can be used to add only the values other than the expression or column.
- If there are no matching rows,
SUM()
returns NULL
.
The query would be written more or less like this:
SELECT
SUM(cantidad*valor_unitario) total
FROM calcular_20170906
WHERE no_recibo=11
;
CREATE TABLE IF NOT EXISTS calcular_20170906 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
no_recibo INT,
cantidad INT,
valor_unitario DECIMAL(12,2)
);
INSERT INTO calcular_20170906 (no_recibo, cantidad, valor_unitario)
VALUES
(10,1,6000),
(11,1,50000),
(11,1,10000),
(11,2,100000)
;
SELECT
SUM(cantidad*valor_unitario) total
FROM calcular_20170906
WHERE no_recibo=11
;
Resultado:
total
260000,00
Using PHP
You would have to get all the rows, without using GROUP BY
or group them by combining GROUP BY
and GROUP_CONCAT
and then go through the values and add them.
In my opinion it's not worth it, if you only need the total.