【问题标题】:Sum grouped by multiple columns in MySQL在 MySQL 中按多列分组的总和
【发布时间】:2012-11-29 15:43:35
【问题描述】:

我有下表

color       shape         material       value    qt
----------------------------------------------------
green       cylinder      plastic         12       2
white       cube          wood            5        1
green       cylinder      plastic         6        2
white       cube          wood            5        2
green       cylinder      plastic         2        2

我想要具有相同标准的值的总和。我想要类似下面的东西。

color       shape         material       sum
-----------------------------------------------
green       cylinder      plastic        28
white       cube          wood           15
green       cylinder      plastic        12

我有很多颜色、形状和材料,所以我想要一个动态查询。我不知道从哪里开始。

编辑

还有其他一些特征使每条记录都不同

【问题讨论】:

  • 你是如何计算这些值的?
  • 第一个和第三个绿色圆柱体的区别?
  • 是的,因为它们还有其他未在此处显示的特征
  • 好吧,你最好在这里展示它们,因为它们似乎对于找到正确的解决方案很重要。
  • 如果您不显示所有信息,我们如何帮助您?

标签: mysql sum pivot


【解决方案1】:

如果它和你的描述一样简单

SELECT color, shape, material, SUM(value)
FROM SomeTable
GROUP BY color, shape, material

但不确定您的示例输出表是否与您的描述和原始数据相关

【讨论】:

    【解决方案2】:
    select color, shape, material, sum( value * qt )
    from tbl
    group by color, shape, material
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多