我在从另一个表添加多个列值时遇到问题,并作为添加的列返回到结果中。
这是我的第一张表。
attID | val1 | val2 | val3 | att |
-----------+---------+---------+----------+---------+
1 | 10 | 10 | 10 | P |
1 | 20 | 20 | 20 | M |
1 | 30 | 30 | 30 | HA |
2 | 1 | 1 | 1 | P |
2 | 2 | 2 | 2 | M |
2 | 3 | 3 | 3 | HA |
我的第二张表是
ID | name | attID |
---------+--------+---------+
101 | luke | 1 |
102 | zik | 2 |
我想要的结果是:
ID | name | P | M | HA |
-----+--------+--------------+----------+------------+
101 | luke | 30 | 60 | 90 |
102 | zik | 3 | 6 | 9 |
列val1 val2和val3由att添加,并作为另一列添加到结果表中
这是我的解决方案
select
ID, Name,
(val1 + val2 + val3) P,
(val1 + val2 + val3) M,
(val1 + val2 + val3) HA
from
t1, t2
where
t1.attid = t2.addid
group by
att
我尝试了很多次,但无法找到解决方案
如果有人能给我真正的解决方案,请提前感谢
答案 0 :(得分:1)
您可以使用join
,聚合和一些算术执行此操作:
select t2.ID, t2.name ,
sum(case when att = 'P' then val1 + val2 + val3 end) as P,
sum(case when att = 'M' then val1 + val2 + val3 end) as M,
sum(case when att = 'HA' then val1 + val2 + val3 end) as HA
from t2 left join
t1
on t2.attId = t1.attId
group by t2.ID, t2.name ;
在您的示例中,没有值为NULL
。如果是这种情况,您需要小心并使用coalesce()
。我想我会推荐一个子查询:
select t2.ID, t2.name ,
sum(case when att = 'P' then val end) as P,
sum(case when att = 'M' then val end) as M,
sum(case when att = 'HA' then val end) as HA
from t2 left join
(select t1.*,
(coalesce(val1, 0) + coalesce(val2, 0) + coalesce(va3, 0)
) as val
from t1
) t1
on t2.attId = t1.attId
group by t2.ID, t2.name ;