我试图找出如何根据与这些列相邻的另一列的条件将多个列的值相加的方法。
我已经尝试过将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
Apples | 2.2 | Oranges | 5.1
Oranges | 3.1 | Apples | 1.7
我希望我的输出看起来像这样:
Produce | TotalWeight
Apples | 3.9
Oranges | 8.2
答案 0 :(得分:3)
想到一个子查询和聚合:
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;