MySQL SUM同一行中的多个列

时间:2019-06-26 14:31:57

标签: php mysql

+---------------+---------+-----------------+---------+ 
| product_count | size1   | sproduct_count2 | size2
+---------------+---------+-----------------+---------+ 
|            13 | 2x4     |               5 |     2x6 
|            14 | 2x6     |               2 |     4x8 
|            15 | 2x8     |               3 |     2x8 
|            16 | 4x4     |               2 |     4x4 
|            17 | 4x8     |              15 |     4x8
+---------------+---------+-----------------+---------+

如何获取总数,所以返回结果如下:

product_count | size
           13 | 2x4
           19 | 2x6
           18 | 2x8
           18 | 4x4
           34 | 4x8

我尝试过:

SELECT SUM(product_count+product_count2) AS product_count, size1 FROM UNITS GROUP BY size1

,它适用于某些行,而不适用于某些行。我需要使用CONCAT吗?

2 个答案:

答案 0 :(得分:3)

您需要汇总2列的并集:

select sum(t.product_count) product_count, t.size from (
  select product_count, size1 size from units
  union all
  select sproduct_count2, size2 from units
) t
group by t.size

请参见demo
结果:

| product_count | size |
| ------------- | ---- |
| 13            | 2x4  |
| 19            | 2x6  |
| 18            | 2x8  |
| 18            | 4x4  |
| 34            | 4x8  |

答案 1 :(得分:0)

select u1.product_count + if(u2.product_count is null,0,u2.product_count) as product_count,u1.size1 as size
from units u1
left join (select sum(sproduct_count2) as product_count,size2 
from units
group by size2) u2
on u1.size1 = u2.size2;

演示: https://www.db-fiddle.com/f/8TfoNen5toVHvy4DbBe7M6/0

  • 您可以首先将sproduct_count2和{{1}上的size2上的所有计数相加。
  • 然后,您可以对group by表本身对上述结果进行size2,并附加一个left join条件检查,以防万一您发现其中不存在units if(在这种情况下,您可以添加0)。

注意::此操作仅过滤size1中出现的值(具有适当的计数),以查看您尝试过的查询(size2