Sql 如何根据相邻列的条件,将不同列的值相加?
我试图找出如何根据与多个列相邻的另一列的条件,将多个列中的值相加 我曾尝试在专栏中使用UNION,但我还没有找到最好的方法,而且我也不完全确定这是否是正确的方法,因为我从这里开始陷入困境Sql 如何根据相邻列的条件,将不同列的值相加?,sql,Sql,我试图找出如何根据与多个列相邻的另一列的条件,将多个列中的值相加 我曾尝试在专栏中使用UNION,但我还没有找到最好的方法,而且我也不完全确定这是否是正确的方法,因为我从这里开始陷入困境 select [Produce 1], [Weight 1] as columns from table union select [Produce 2], [Weight 2] from table 根据我的样本数据: Produce 1 | Weight 1 | Produce 2 | Weight 2
select [Produce 1], [Weight 1] as columns from table
union
select [Produce 2], [Weight 2] from table
根据我的样本数据:
Produce 1 | Weight 1 | Produce 2 | Weight 2
Apples | 2.2 | Oranges | 5.1
Oranges | 3.1 | Apples | 1.7
我希望我的输出如下所示:
Produce | TotalWeight
Apples | 3.9
Oranges | 8.2
我想到了子查询和聚合:
select produce, sum(weight)
from (select [Produce 1] as produce, [Weight 1] as weight from table
union all
select [Produce 2], [Weight 2] from table
) t
group by produce;
UNION ALL
在这里可能是更好的选择,因为我想如果两个橘子(或苹果)的重量恰好相同,他们就不想拿出一堆橘子(或苹果)。@stickybit。我同意。谢谢,谢谢你们两位!是的,我使用Union就是因为这个。非常感谢!