对多行中的多个列求和

m4pnthwp  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(264)

我有以下销售数据结构:

id  year  M01  M02  M03  M04  M05 M06 M07 M08 M09 M10 M11 M12
 1  2020    0    5    4    0   10   0   0   0   0   0   0   0
 1  2019    4    3    0    0    6   0   7   0   8   0   0  10
 2  2020    0    5    4    0   10   0   0   0   0   0   0   0
 2  2019    4    3    0    0    6   0   7   0   8   0   0  10

我需要知道在过去的12个月里售出了多少个id=1的产品。如果我们在2020年6月,我需要求m01、m02、m03、m04、m05(其中年份=2020)和m06、m07、m08、m09、m10、m11、m12(其中年份=2019)之和,其中id=1。我应该得到36的值。
请问,对于如何在mysql中做到这一点有什么建议吗?

mhd8tkvw

mhd8tkvw1#

你需要修正你的数据模型。取消拆分然后聚合:

with reasonable_format as (
      select id, year, str_to_date(concat(year, '-01-01'), '%Y-%m-%d') as date, m01 as amount from sales union all
      select id, year, str_to_date(concat(year, '-02-01'), '%Y-%m-%d') as date, m02 from sales union all
      . . .
      select id, year, str_to_date(concat(year, '-02-01'), '%Y-%m-%d') as date, m12 from sales 
    )
select sum(amount)
from reasonable_format rf
where id = 1 and date <= curdate - interval 1 year;
``` `reasonable_format` 就是你的数据应该是什么样子。

相关问题