SQL 按多个id对多列求和

SQL sum multiple columns by multiple id

我想通过多个列和 ID 对 table 求和。

我的 table (这是 2 table 的连接)看起来像这样:

unique_ID, year, ID1, Amount1, ID2, Amount2, ID3, Amount3, ... , ID6, Amount6;

我需要获得 ID 匹配 (ID1=ID2=...=ID6) 的总金额 (Amount1+Amount2+...+Amount6)

所以结果 table 看起来像这样: Year, ID1(/ID2/.../ID6), Amount1 + ... + Amount6

示例数据:(由 excel 制作)

Source table                                    
UID     YEAR    ROOM1       AMOUNT1 ROOM2       AMOUNT2
15823   2015    Material1   1       Material3   8
15298   2015    Material1   2       Material3   9
22405   2015    Material2   3       Material4   10
22403   2015    Material2   4       Material5   11
22404   2015    Material2   5       Material5   12
25417   2016    Material1   6                   0
31435   2016    Material2   7       Material2   13

Result table        
YEAR    Material    AMOUNT
2015    Material1   3
2015    Material2   12
2015    Material3   17
2015    Material4   10
2015    Material5   23
2016    Material1   6
2016    Material2   20

解释: 我有一个很大的 table 产品,其中每个产品最多可以包含 6 个原始 material。 (ID 1-6 标识material,Amount 1-6 表示使用量material)。 materials 的顺序可以变化。 我需要知道按年和 materials 使用的 materials 的数量。

我有一半的解决方案需要在 excel 中进行大量的后续工作。 在SQL中有什么简单而优雅的解决方案吗?

我正在使用 Firebird,但如有任何帮助,我们将不胜感激。

提前致谢!

您似乎想要每年的总金额 material。所以首先得到一个合适的 material/year table on-the-fly,然后聚合:

select 
  year,
  material_id,
  sum(amount) as total
from
(
  select year, id1 as material_id, amount1 as amount from mytable
  union all
  select year, id2 as material_id, amount2 as amount from mytable
  union all
  select year, id3 as material_id, amount3 as amount from mytable
  union all
  select year, id4 as material_id, amount4 as amount from mytable
  union all
  select year, id5 as material_id, amount5 as amount from mytable
  union all
  select year, id6 as material_id, amount6 as amount from mytable
) materials
where material_id is not null
group by year, material_id
order by year, material_id;