Skip to content
Advertisement

Sum multiple columns in multiple rows

I have following data structure for sales:

I need to know how many products with id=1 were sold for the last 12 month. If we are in June 2020 I need to sum M01, M02, M03, M04, M05 (WHERE year=2020) and M06, M07, M08, M09, M10, M11, M12 (WHERE year=2019) WHERE id=1. I should get a value of 36.

Please, any suggestions on how to do that in MySQL?

Advertisement

Answer

You need to fix your data model. Unpivot and then aggregate:

reasonable_format is what your data should look like.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement