Skip to main content
1 de 3

MySQL SUM same id in different columns

the problem is this:

I have a table where I register 5 different products, a product can be both in the field product_1 in the product_5, what I need is to add the quantity of each product and group it by id.

This is the structure of the table. *-----------------++ |ID | |DATE | |ID_PRODUCT_1 | |QUANTITY_PRODUCT_1| |ID_PRODUCT_2 | |QUANTITY_PRODUCT_2| |ID_PRODUCT_3 | |QUANTITY_PRODUCT_3| |ID_PRODUCT_4 | |QUANTITY_PRODUCT_4| |ID_PRODUCT_5 | |QUANTITY_PRODUCT_5| +------------------+

And these are some example records, what I need is to add the quantity of the product with id = 1001, although this id exists in the other records, but in a different field, and also sum the other products respectively.

    *--------------------------------+
    |ID                 = 1          |
    |DATE               = 2017-02-03 |
    |ID_PRODUCT_1       = 1001       |
    |QUANTITY_PRODUCT_1 = 1400       |
    |ID_PRODUCT_2       = 1002       |
    |QUANTITY_PRODUCT_2 = 600        |
    |ID_PRODUCT_3       = -          |
    |QUANTITY_PRODUCT_3 = -          |
    |ID_PRODUCT_4       = -          |
    |QUANTITY_PRODUCT_4 = -          |
    |ID_PRODUCT_5       = -          |
    |QUANTITY_PRODUCT_5 = -          |
    +--------------------------------+

    *--------------------------------+
    |ID                 = 2          |
    |DATE               = 2017-02-03 |
    |ID_PRODUCT_1       = 1003       |
    |QUANTITY_PRODUCT_1 = 1400       |
    |ID_PRODUCT_2       = 1001       |
    |QUANTITY_PRODUCT_2 = 1000       |
    |ID_PRODUCT_3       = -          |
    |QUANTITY_PRODUCT_3 = -          |
    |ID_PRODUCT_4       = -          |
    |QUANTITY_PRODUCT_4 = -          |
    |ID_PRODUCT_5       = -          |
    |QUANTITY_PRODUCT_5 = -          |
    +--------------------------------+
    *--------------------------------+
    |ID                 = 3          |
    |DATE               = 2017-02-03 |
    |ID_PRODUCT_1       = 1002       |
    |QUANTITY_PRODUCT_1 = 1400       |
    |ID_PRODUCT_2       = 1003       |
    |QUANTITY_PRODUCT_2 = 600        |
    |ID_PRODUCT_3       = 1001       |
    |QUANTITY_PRODUCT_3 = 200        |
    |ID_PRODUCT_4       = -          |
    |QUANTITY_PRODUCT_4 = -          |
    |ID_PRODUCT_5       = -          |
    |QUANTITY_PRODUCT_5 = -          |
    +--------------------------------+

so that in the end this Is the result:

SUM(PRODUCT WITH ID 1001) = 2600 SUM(PRODUCT WITH ID 1002) = 2000 SUM(PRODUCT WITH ID 1003) = 2000