学到一寸是一寸 2022-01-28 14:19 采纳率: 66.7%
浏览 33
已结题

Mysql怎么将将分组聚合的查询结果写入另一个表

Mysql中怎么把分组聚合的查询结果(左边)插入到新表中实现下图这样的效果(右边)?

img

  • 写回答

3条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-01-28 14:49
    关注

    通用方法一般是用case when 来处理行列转换的问题

    select time,
    sum(case when fruit='apple' then number else 0 end ) apple,
    sum(case when fruit='pear' then number else 0 end ) pear,
    sum(case when fruit='peach' then number else 0 end ) peach,
    sum(case when fruit='orange' then number else 0 end ) orange,
    sum(number) total
    fromgroup by time
    

    可惜mysql不支持pivot,否则也不用写得这么麻烦

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月5日
  • 已采纳回答 1月28日
  • 创建了问题 1月28日