I have the following information in a MySQL table, what I need is to calculate the total by adding the result of multiplying the quantity by the corresponding price.
If it Precio con descuento
is different from NULL
it will be used to make the calculation.
| Cantidad | Precio | Precio con descuento |
|------------|--------|----------------------|
| 1 | 10 | NULL |
| 2 | 10 | 5 |
| 10 | 2 | 1 |
1 * 10 = 10
2 * 5 = 10
10 * 1 = 10
TOTAL: 30
Currently I have:
SELECT cantidad, precio, precio_descuento FROM ventas WHERE cerrado = 1;
You can use the function
coalesce()
to multiply by one or the other.The function
coalesce()
can take N parameters and returns the value of the first parameter that is notnull
. In this case, it will return the value ofprecio_descuento
if is notnull
, and if it is, the value ofprecio
.Another possibility is to use a statement
case
to determine which field to use:Finally, you can use a function
if()
to achieve the same resultIf you want the total of all sales, apply the aggregate function
sum()
on this calculated value, for example: