Mysql 对多行中的多个列求和

Mysql 对多行中的多个列求和,mysql,sql,aggregate-functions,Mysql,Sql,Aggregate Functions,我有以下销售数据结构: 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

我有以下销售数据结构:

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中实现这一点,您有什么建议吗?

您需要修复数据模型。取消PIVOT,然后聚合:

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;

合理的格式是您的数据应该是什么样子。

我强烈建议不要使用这种非规范化的表。我建议使用月份和值字段对其进行规范化。这只是许多未来复杂性的开始。上面的表格应该只是一个视图。不幸的是,我必须处理这个结构。。。非常感谢戈登·林诺夫!你救了我。唯一的更正:日期>=curdate-间隔1年。好吧,由于旧的MySQL版本,我不得不引入更多的修改,但是,原则上,这就是我想要的。