简体   繁体   English

MySQL SUM同一行中的多个列

[英]MySQL SUM multiple columns in same ROW

+---------------+---------+-----------------+---------+ 
| 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
+---------------+---------+-----------------+---------+

How do I get the total counts so the return results appear like: 如何获得总数,所以返回结果如下所示:

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

I have tried: 我努力了:

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

and it works for some rows and others it does not work for. 它适用于某些行,而不适用于某些行。 Would CONCAT be something I need to use? CONCAT是我需要使用的东西吗?

You need to aggregate on the union of the 2 columns: 您需要汇总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

See the demo . 参见演示
Results: 结果:

| product_count | size |
| ------------- | ---- |
| 13            | 2x4  |
| 19            | 2x6  |
| 18            | 2x8  |
| 18            | 4x4  |
| 34            | 4x8  |
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;

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

  • You could first sum up all counts from sproduct_count2 with size2 with a group by on size2 . 你可以先从总结所有罪状sproduct_count2size2group bysize2
  • You could then do a left join on the above result with the units table itself with an additional if condition check if in case you find a size1 not there in size2 (in which case you could add a 0). 然后,可以对上面的结果与units表本身进行left join ,并进行额外的if条件检查,以防万一您发现size1不存在size2 (在这种情况下,您可以添加0)。

Note: This only filters values appearing in size1 (with it's appropriate counts) looking at the query you tried ( SUM(product_count+product_count2) AS product_count, size1 FROM ) 注意:此选项仅过滤出现在size1值(具有适当的计数),以查看您尝试的查询( SUM(product_count+product_count2) AS product_count, size1 FROM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM