I have a table called products, the products are registered with a single sku and in a column called quantity there are the stocks, I want to add all the records that are in the quantity column but only add those of the same sku, this is my table:
*----*---------*----------*----------*
| id | sku | nombre | cantidad |
*----*---------*----------*----------*
| 1 | 1001 | Refresco | 20 |
*----*---------*----------*----------*
| 2 | 1002 | Papas | 100 |
*----*---------*----------*----------*
| 3 | 1003 | Tortillas| 15 |
*----*---------*----------*----------*
| 4 | 1001 | Refresco | 70 |
*----*---------*----------*----------*
| 5 | 1003 | Tortillas| 30 |
*----*---------*----------*----------*
| 6 | 1001 | Refresco | 20 |
*----*---------*----------*----------*
The code I am applying is:
SELECT SUM(IF(sku=1001, cantidad)) FROM productos;
Send this error:
syntax error near unexpected `if' element
You could do it like this:
sku
andnombre
SUM()
you pass to the columncantidad
sku
and bynombre
WHERE
wheresku
= 1001AND
If you want the sum to be made for all the products, grouping them by their
sku
then just remove the oneWHERE
from your query, leaving it like this:Now with your same syntax I think the change should look like this:
For what you want you can select the sum of the data grouping by the column you want, of course, conditioning by the code, functional example;
Practical example of your data; http://sqlfiddle.com/#!9/74b870/2
You may wonder how to do the same with several
sku
, the solution is to use the clauseIN
;