mysql根据列条件对行和列求和的查询

xam8gpfp  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(348)

请帮助我为以下条件编写查询。我有一张我列在下面的table

ID  Wt1  Wt1_Type  Wt2  Wt2_Type  Wt3   Wt3_Type  Wt4  Wt4_Type
--------------------------------------------------------------
1   200  1         220  1         300   2         400  3    
2   100  4         150  3         100   5         120  1  
3   100  3         110  1         200   5         100  4

我需要一个查询来对分组在权重类型(wt1\u类型、wt2\u类型、wt3\u类型、wt4\u类型)上的所有权重(wt1、wt2、wt3、wt4)求和。
输出应该如下所示

Wt_type   Total
1         650
2         300
3         650
4         200
5         300

有人能帮我起草一个mysql查询来得到这个结果吗?
谢谢

eagi6jfj

eagi6jfj1#

我建议使用更好的表设计,而不是使用@fa06来给出答案,因为它应该适合您。以下是您应该如何存储数据:

ID  Type Wt
-------------
1   1    200
2   4    100
3   3    100
4   1    220
5   3    150
6   1    110
7   2    300
8   5    100
9   5    200
10  3    400
11  1    120
12  4    100

请注意,只有一列存储类型,另一列存储该类型的权重。现在,您的预期输出只需要一个非常简单的查询:

SELECT Type, SUM(Wt) AS Total
FROM yourTableUpdated
GROUP BY Type;

数据库非常擅长跨行执行操作,更不用说跨列了。

3pmvbmvn

3pmvbmvn2#

您可以在下面尝试使用UNIONALL和subquery

select Wt_Type,sum(Wt) as total from
(
   select Wt1_Type as Wt_Type,Wt1 as Wt from tablename
   union all
   select Wt2_Type ,Wt2 from tablename
   union all
   select Wt3_Type ,Wt3 from tablename
   union all
   select Wt4_Type ,Wt4 from tablename
)A group by Wt_Type
oiopk7p5

oiopk7p53#

用这个应该可以工作

select Wt_Type,sum(Wt) as total from ( select Wt1_Type as Wt_Type,Wt1 as Wt from tablename union all select Wt2_Type ,Wt2 from tablename union all select Wt3_Type ,Wt3 from tablename union all select Wt4_Type ,Wt4 from tablename )A group by Wt_Type

相关问题